Intro Java Rev010

103
JAVA ESSENTIALS BY RICH HELTON (SUN CERTIFIED (SC) JAVA PROGRAMMER, SC JAVA DEVELOPER, SC ENTERPRISE ARCHITECT) January 2009

Transcript of Intro Java Rev010

Page 1: Intro Java Rev010

JAVA ESSENTIALSBY RICH HELTON

(SUN CERTIFIED (SC) JAVA PROGRAMMER, SC JAVA DEVELOPER, SC ENTERPRISE ARCHITECT)

January 2009

Page 2: Intro Java Rev010

Java, the beginning …

During the 1990's, frameworks and memory usage was a common issue with C and C++.

With C and C++ frameworks, there were no standard frameworks that were distributed with the language. Each company and compiler had multiple frameworks for different pieces.

It was not uncommon to have a framework for parsing, and a different one for networks.

It was even a common practice for developers to write their own memory routines to handle dangling pointers. Programmers were spending enormous amounts of time in a constant battle to get a program to remember to de-allocate its memory. Often times, a program would move its execution scope and forget its previous references to pointers.

This caused programs to dangle pointers in memory no longer accessible in the program. Pointers would eat up the memory until a reboot is done to clear out the unreferenced pointers (memory).

Page 3: Intro Java Rev010

Java, the beginning …

Java provided a common framework as part of the language to handle strings, networks, and extended functions.

Java also no longer used pointers, and created the Java Virtual machine to have the language run in a virtual container that executed garbage collection to look for dangling pointers and clear the memory no longer in use.

Java also provided Object Oriented Programming where the framework and pieces were used as objects to abstract the details.

The various pieces of objects could be combined into new combinations, normally known as design patterns, to produce new functionality.

Page 4: Intro Java Rev010

Java, the history …

Version Year New Features

1.0 19961.1 1997 Inner classes1.2 1998 Swing, Collections

1.3 2000 Performance enhancements

1.4 2002 Assertions, XML5 2004 Generic classes,

enhanced for loop, auto-boxing, enumerations

6 2006 Library improvements

Page 5: Intro Java Rev010

My First Java Program…

public class MyFirstJavaProgram {

// Start the programpublic static void main(String[] args){

if(args.length >0){ // If argument print nameString myName = (String) args[0];System.out.println("Hello " +myName);

}else{ // Else printSystem.out.println("Hello there");

}}

}

Page 6: Intro Java Rev010

Find it your java program…

At the command prompt :

Page 7: Intro Java Rev010

Find the compiler…

At the command prompt, check to make sure that the JDK is set for compiling :

At the command prompt, the JDK is set in the environment for compiling :

Page 8: Intro Java Rev010

Compile…

At the command prompt, run the java compiler “javac”:

Page 9: Intro Java Rev010

Run the program…

At the command prompt, run the java program without the argument, “java” runs the program:

Page 10: Intro Java Rev010

LET’S BREAK DOWN THE PROGRAM

Page 11: Intro Java Rev010

Components of this application…

CommentsReserved wordsModifiersStatementsBlocksClassesMethodsThe main method

Page 12: Intro Java Rev010

Comments

Comments are used to communicate the purpose of parts of the program in the code.

Comments are not executed as part of the code and are ignored by the compiler.

Using the (//) double slashes will tell the compiler to ignore the entire line.

Using the (/*) slash star will start the compiler to ignore the comment until it meets the ending slash star (*/).

Here are the two types of comments:// Start the program, single line comment/* Start the program, multiple line comment */

Page 13: Intro Java Rev010

Reserved Words

Reserved words, or keywords, are words with special meaning that define how the program should behave in the compiler.

These are words will explain to the compiler how to construct the program.

Being reserved to the compiler, these words cannot be duplicated anywhere else in the code as class names, variable names, or method names.

Words in the program, such as “public class” tells the compiler to construct the class with scope of “public” protection.

Java keywords are case sensitive, so care must be taken in ensuring the case is consistent with the language specification.

Page 14: Intro Java Rev010

Sample Reserved Words

public class MyFirstJavaProgram {

// Start the programpublic static void main(String[] args){

if(args.length >0){ // If argument print nameString myName = (String) args[0];System.out.println("Hello " +myName);

}else{ // Else printSystem.out.println("Hello there");

}}

}

Page 15: Intro Java Rev010

Modifiers, or Access Modifiers

Modifiers define the protection and global or local scope of a class, method or variable.

There are modifiers for controlling access to a class, method, or variable: public, protected, and private

The static modifier can be used for defining a one of a kind global class, method or variable.

The final modifier for finalizing the implementations of classes, methods, and variables. In other words, I defines a constant that once set will never change.

The abstract modifier is used for defining classes and methods without creating the instance of the object. It forces rules on classes.

The synchronized and volatile modifiers, which are used for threads.

Page 16: Intro Java Rev010

Public, Protected and Private

When the “public” access modifier, or keyword, is placed in front of classes or methods, it gives all other pieces of the program access to the method or classes.

When the “protected” access modifier, or keyword, is placed in front of classes or methods, it gives the child class access to that class or method but no one else.

When the “private” access modifier, or keyword, is placed in front of classes or methods , it means that no other class may have access to that class or method.

Page 17: Intro Java Rev010

Sample Modifiers

public class MyFirstJavaProgram {

// Start the programpublic static void main(String[] args){

if(args.length >0){ // If argument print nameString myName = (String) args[0];System.out.println("Hello " +myName);

}else{ // Else printSystem.out.println("Hello there");

}}

}

Page 18: Intro Java Rev010

Statements

A statement is line for a singe unit of work.A line in Java is ended with ( ; ) semicolon.Sample statements from the “MyFirstJavaProgram”:

String myName = (String) args[0];System.out.println("Hello " +myName);

Page 19: Intro Java Rev010

Blocks

A block is a group of actions that is normally defined in a class as the higher level made up of multiple functions.

A block is started with the ( { ) opening brace and ends with the ( } ) closing brace.

Page 20: Intro Java Rev010

Sample Block

Page 21: Intro Java Rev010

Main method

Every Java program must have a “main” method. There is only one “main” method in every Java program.The “main” method is where the program starts it’s

execution, and the closing brace ( } ) of the “main” method is where the program will end.

In the previous slide, the “Method block” of the “main” method is the execution of the program itself.

Page 22: Intro Java Rev010

Main method

Every Java program must have a “main” method. There is only one “main” method in every Java program.The “main” method is where the program starts it’s

execution, and the closing brace ( } ) of the “main” method is where the program will end.

In the previous slide, the “Method block” of the “main” method is the execution of the program itself.

Page 23: Intro Java Rev010

What is a class?

A class is a definition of a group of methods, variables, state and behavior.

In the sample, the class is MyFirstProgram. As MyFirstProgram it can contain variables, methods,

state and behavior that are defined. In this case it simply prints “Hello” and “Hello” with an argument.

The idea of a class is that is can define a car, a catalog, and another group of a construct.

The class can create subgroups, like a car class can have sub classes of itself like “blue car” or “compact car” to define the construct in more detail.

When a class is created and started, called instatiation, it becomes an object. A class can create many objects.

Page 24: Intro Java Rev010

A BRIEF INTRODUCTION INTO

OBJECT ORIENTED PROGRAMMING (OOP)

Page 25: Intro Java Rev010

A brief introduction to OOP

Learning Object Oriented Programming is as easy as PIE.PIE stands for Polymorphism, Inheritance and

Encapsulation.These PIE characteristics provide common properties like

re-use of pieces, hiding of internal data, and propagating characteristics of objects into other objects.

Don’t think that these code pieces are static in nature because the Business Objects can morph into new types of Business Objects as long as their constructs are defined.

Using this fluid style of programming, relational tables can be defined and created by simply defining the initial Business Object.

These concepts are expanded to create morphing viruses where a virus changes itself every time it hits a new machine so that it is a completely different characteristics after multiple propagations.

Page 26: Intro Java Rev010

Polymorphism

Polymorphism started a term in biology for how different types of species have the same generic traits.

It states that the same species may morph, having different qualities, in the same habitat.

For instance, the lady bug may morph into red spots or black spots in the same environment.

The commonality is that the two bugs are still lady bugs, but have different traits like spot colors.

Even though it has different spot colors, it is still lady bug, and flies like a lady bug, eats like a lady bug and does what lady bugs do.

When it no longer does the things a lady bug does, it is a different bug. That is when the bug morphs outside its common species definition.

Page 27: Intro Java Rev010

Polymorphism

In OOP, polymorphism is the ability of different objects, that are created by the same generic class, or traits, to be used the same across the same generic interface but still have different, or morphed, properties.

Let’s use an example, if we have a “Toyota” truck and “Ford” truck created with it’s parent class “Truck”.

Page 28: Intro Java Rev010

Polymorphism, continuing…

Now, let’s create a program called “Midas Touch” that handles the Truck objects and rotates their tires.

class public MidasTouch{

Truck myTruck = new (Truck) Toyota ();

} The program “Midas Touch” can rotate the tires,

regardless if it is a Toyota or Ford Truck object. The factory “Midas Touch” works with trucks but doesn’t have a preference over what type of truck it works on. Even though the Toyota or Ford Truck might have some different techniques for rotating tires, the factory will accept and work on any Truck object.

… rotateTires(myTruck);

Page 29: Intro Java Rev010

Inheritance

Inheritance has to do more with genealogy and parentage.This concept is to understand an objects behavior and

traits by its inherited lineage. A “child” class has a “parent” class that gave it many

default properties. For example, my parents gave me “brown hair” because

they had brown hair, so I, the “child” class inherited my hair color from my “parent” class.

However, after being executed in the program, the program may change the hair color of the “child” class if the protection of the class allows it. For example, if I am indifferent to my hair color in real life, I could dye it if someone prompted me, but regardless, my hair started out brown and may return to its brown state.

Page 30: Intro Java Rev010

Inheritance

In the picture:

The Toyota and Ford are derived, or child classes, from their parent “Truck”

Because the “Toyota” object and “Ford” object inherited properties from its parent, we know that some traits are given to the child classes when they are created.

These Truck parent may have passed on to Toyota and Ford that they had an engine, 4 tires, a windshield, gas tank, brakes, etc.

Page 31: Intro Java Rev010

Inheritance, continuing…

Now, let’s use create a class from the parent class.

class public Truck {

Brakes myBrakes;

Engine myEngine;

Windsheild myWindSheild;

}

class public Toyota extends Truck{

// Already has myBrakes, myEngine, myWindsheild defined.

}

Page 32: Intro Java Rev010

Encapsulation

Encapsulation is also referred to as data hiding or information hiding.

Even though you may see the business object and its methods, you may not call or manipulate the inside data directly, or at all, unless you call a specific method.

Many objects may use a constructor to pass information into the object that it cannot retrieve without using a “getter( )” method.

For example, I could create a “Ford Truck” object, and it will have many properties like color, bed type, bin number, etc.

It will also have embedded objects like tires, windshields, radio, seats, etc.

In order to get data from the “Ford Truck” object, I need to call an getter method that it shows me like “getTirePressure( )” to return an integer of 35 for 35 psi.

Page 33: Intro Java Rev010

Putting it all together

OOP introduced a new way of developing programs. Before OOP, programming was very procedural and

structural. When writing a program in the “C” language, I had to now

all the pieces of the program and what side effects it would cause.

When moving to Java, I could piece meal the program so that one person did one set of objects and I could do another set of objects.

What became important in Object Oriented Design, is now the pieces of the program was merely a collection of objects.

The Architect no longer had to focus on the code, but simply the properties and the interfaces to the objects. The code became an abstract collection of classes.

Many of these properties were later even entered into property files, and text messages which gave birth to Service-Oriented Architecture (SOA).

Page 34: Intro Java Rev010

2nd Java Sample Program with an object

Let’s create an class from the first program, and call it MyFirstObject:

class MyFirstObject{String myName;MyFirstObject(){// Constructor

myName = "there";}//Settervoid setName(String myName){

this.myName = myName;}//GetterString getName(){

return this.myName;}

}

Page 35: Intro Java Rev010

Some new terms

There are various terms that this program will add to our vocabulary, there are “setters”, functions that set variables, and “getters”, functions that get variables.

The Constructor is the method used to create the object. There could be multiple constructors, taking in different arguments as they “overload” their methods.

Overloading is when a method with the same name, but a different argument, is called based in it’s argument.

Also, introduced is the “this” pointer, or keyword, used in Java reflection.

“this” allows an object to look into the current instance of itself.

In other words, when the class becomes a object, I has state, variables, methods and information about itself, by using “this”, the class can manipulate its current data.

Page 36: Intro Java Rev010

2nd Java Program object creation

In the code, there must always be one and only one “main” method that starts the execution.

The “main” method is static, which means that it is the only one. The execution of the program will load objects, and the “new” keyword will create our first object, “myObj”, from the “MyFirstObject” class.

After the “myObj” is created, we set the name if there is one passed through the argument, otherwise, it will return the default name “there”.

Note: Even if a Constructor is not defined in code, a default one is always defined by the compiler. The “new” keyword must call a constructor to create an object from a class.

Page 37: Intro Java Rev010

2nd Java Program object creation

Always remember that an object is never created, or instantiated, unless the “new” keyword is used. Let’s create the object:

public class MySecondJavaProgram {public static void main(String[] args){

MyFirstObject myObj = new MyFirstObject();if(args.length >0){ // If argument print name

myObj.setName(args[0]);}System.out.println("Hello " + myObj.getName());} // End Main

}

Page 38: Intro Java Rev010

What happened

From this program, “MySecondJavaProgram”, we were able to create an object with the “new” keyword.

The object didn’t add much functionality than the first program, however, we can use the object across many programs, and start creating a framework of libraries.

A main purpose of OOP is reusability.Another concept is also cleaner code construction.

Because of the movement of the functionality of the program into a separate object, the code becomes compartmentalized.

Page 39: Intro Java Rev010

Extending functionality

Let’s extend the functionality of the first object, with the “extend” keyword, and create a child class:

class MySecondObject extends MyFirstObject{String myComment;

// ConstructorMySecondObject(){ myComment = "No Argument";}//Settervoid setComment(String myComment){

this.myComment = myComment;}//GetterString getComment(){

return this.myComment;}

}

Page 40: Intro Java Rev010

Extending functionality

The program will create 2 objects now, the child object “MySecondObject” will create a “MyFirstObject” when created and use it’s functionality:

public class MyThirdJavaProgram {public static void main(String[] args){

MySecondObject myObj = new MySecondObject();if(args.length >0){ // If argument print name

// From parentmyObj.setName(args[0]); // From childmyObj.setComment("Argument found");

}System.out.println("Hello " + myObj.getName());

} // End Main}

Page 41: Intro Java Rev010

Extending functionality

By extending functionality in a new object, I was able to add methods and variables without changing the initial code and how it works.

This becomes monumental when creating frameworks because now libraries can be extended without changing original functionality.

A new concept that can be introduced here is called “Overrriding”.

Overriding methods occurs when the method of the child class is used instead of the parent.

Since the parent, or super class, had a “setName” method, and the child did not, the parent’s method was used.

The child could “override” the parent’s “setName” method by simply having its own.

Page 42: Intro Java Rev010

SUPER

So far, we have discussed that when a child object is created, the parent object is also created and the child inherits their attributes.

The child object can also get data directly from their parent class using the “super” keyword. Here’s an example where the child object can get the “myName” information directly from their parent://Print the namevoid printName(){

System.out.println("MyFirstObject's name " + super.myName);}

Page 43: Intro Java Rev010

Reflection

The “this” keyword has been briefly discussed. It is an important concept for an object to look at itself in introspection and examine what type of object it is, what state it is in, its current variables, and even its current properties. It is examining its own metadata.

Reflection comes in handy when serializing objects (saving to disk) and writing the objects variables and methods into XML.

The Simple API for XML (SAX) parser using reflection to develop its data definitions and types.

Let’s start the code:import java.lang.reflect.*;public class Reflection1{

public static void main(String[] args) {WhoAmI whoami = new WhoAmI();whoami.WhoAreYou(); } }

Page 44: Intro Java Rev010

Reflection (finding my fields/methods)

class WhoAmI{String test1 ="I think";String test2 = "Therefore I am";void CanYouSeeMe(){}void WhoAreYou(){

System.out.println("WhoAmI:" +this.getClass().getName());

Method [] methods = this.getClass().getDeclaredMethods();

Field [] fields = this.getClass().getDeclaredFields();for(int i =0; i < methods.length;i++) System.out.println("Method:"

+methods[i].getName());for(int i =0; i < fields.length;i++) System.out.println("Field:" +fields[i].getName());

}

Page 45: Intro Java Rev010

Reflection

The code produced its fields and methods. After collecting this information, it could easily be placed

on the network, through XML or serialized to show what is available.

The output:WhoAmI:WhoAmIMethod:WhoAreYouMethod:CanYouSeeMeField:test1Field:test2

Page 46: Intro Java Rev010

Abstract (Must Do)

Not only can a child inherit from their parent, but a child can also be told the interface that they must produce.

This technique is an “interface” which is basically a parent that can “Do as I say and not as I do”.

Here’s an example interface that will force the child class to create the “setName” and “getName” methods:

interface MustDo{public abstract void setComment(String myComment);abstract String getComment();

}class MySecondObject extends MyFirstObject implements

MustDo{The second object will inherit from the first, but it “has to”

create the functionality of the “MustDo” class.

Page 47: Intro Java Rev010

Final (Don’t Change)

In some instances of programming, a constant class, method or variable needs to be defined.

These are variables that do not change once they are set. A class and method can be declared that a child class can

not over write or perform overriding. One example of a variable used in this way:

final boolean DEBUG = false; In this example, a developer may want a “DEBUG”

variable that will be used in the class to decide to perform debug traces or not. In this case you want to force the variable to not be changeable.

During the instance of an object, the static variable can also be added to only allow the creation of the globally:

static final boolean DEBUG = false;

Page 48: Intro Java Rev010

Import

The theme of Java has been abstraction, re-use, and frameworks.

It becomes a daunting task that there are so many frameworks to chose from and many are free.

By default, the “import” keyword is used to pull in other objects and packages into the file. For instance, the “import java.io.*;” statement at the top of the file will give scope to all classes in that the Java IO framework.

Pulling in the entire package does create some overhead on what is being exactly used and what is not, so a more precise definition of the package being used can be given in this example as the “Java IO File” class being referenced by “import java.io.File;”

Page 49: Intro Java Rev010

JAR

There are many frameworks, usually called packages, that come standard with Java.

These frameworks evolve to the Java standard over time.For instance, the Java Cryptography Extensions (JCE)

used to be Java Specification Request (JSR) 27 for some time. This is the framework for encrypting data with Triple-DES, RSA, and multiple algorithms.

During this period, a programmer who wanted to use the JCE.JAR had to download it separately. The package now comes with the J2SE.

The Java Archive (JAR ) file can be used by the program if both the file is associated through a “classpath” and its associated “import” is included.

The “classpath” is a property of the program that contains the paths of all classes.

Page 50: Intro Java Rev010

JAR Example

Page 51: Intro Java Rev010

Java Properties

The program can determine it’s current environmental propeerties by using “System.getProperty()” and set them by “System.setProperty();”.

Here’s some sample code:public class JavaProperty {

public static void main(String[] args) {System.out.println("Classpath:" +

System.getProperty("java.class.path"));System.out.println("Java Version:" +

System.getProperty("java.version"));System.out.println("Java Home:" +

System.getProperty("java.home"));System.out.println("Operating System:" +

System.getProperty("os.name"));System.out.println("User's Home:" +

System.getProperty("user.home"));System.setProperty("user.home", "C:\\Documents and Settings");System.out.println("User's Home:" +

System.getProperty("user.home"));}}

Page 52: Intro Java Rev010

Java Properties

Notice that the “user.home” was changed by the program:Java Version:1.6.0_07Java Home:C:\Program Files\Java\jre1.6.0_07Operating System:Windows XPUser's Home:C:\Documents and Settings\qnwa08User's Home:C:\Documents and Settings

Page 53: Intro Java Rev010

Packages

As we discussed the “import” keyword, it is important to note that this statement defines the class and directory hierarchy in the JAR or file structure. See the JAR picture.

For instance, the JAR has the class “Cipher.class” file in the “javax/crypto/” subdirectory. The import statement will say “import javax.crypto.Cipher” on the calling file.

Part of the import statement tells which subdirectory to find the file starting from the JAR or classpath.

Subsequently, the file had to define this path and subsequent “import” statement by using the “package” keyword:

package javax.crypto;public class Cipher { }

This is very important when creating packages or your own frameworks and to organize them in a directory structure.

Page 54: Intro Java Rev010

INPUT/OUTPUT (I/O)

Page 55: Intro Java Rev010

Strings

A String is an immutable object that contains an array of bytes or characters.

By immutable, it is meant that you cannot modify the String object. You can create new Strings from the object, and when a substring or the String is modified, it is actually creating a new String() object.

A Sample String, “test” is created and then re-created again with a different sequence of characters:

String test = "You cannot change";test = test.toLowerCase();System.out.println(test);

Page 56: Intro Java Rev010

StringBuffer

Re-creating objects can add a lot of overhead to a program. Every time that a program is created, the program allocates the methods and variables of that object in memory.

A simpler method is to use the “StringBuffer” class.The “StringBuffer” class allows its contents to be modified

without creating a new class.Notice in the following that I did not have to create a new

object, the output was “egnahc tonnac uoY”:StringBuffer test = new StringBuffer("You cannot change");test.reverse();System.out.println(test);

Page 57: Intro Java Rev010

Strings

Even though Strings may have some additional overhead, there is a lot of manipulation that can be done with strings in string arithmetic, observe some of the following:

String test ="You" + " cannot " + "change me";int len = "You cannot change me".length();test = " You ";test += "cannot ";test += "change me";

Page 58: Intro Java Rev010

StringTokenizer

The String class is great for a sequence of characters and the StringBuffer class is great for appending and inserting the sequence into the same class but what about tokens.

Tokens are how humans have the tendency to break characters into individual words, or tokens.

The “StringTokenizer”, from the “java.util” package is a utility for breaking down the words of a sentence. Here’s a snippet

String str = "Java,is,Cool";StringTokenizer st = new StringTokenizer(str, ",");while (st.hasMoreTokens()) { System.out.print(st.nextToken()+ " ");The Output is : Java is Cool

Page 59: Intro Java Rev010

Files

When programming Java, it is very important to understand file Input/Output (I/O).

The File class, java.io.File, is used for manipulating the file, while classes like Scanner and FileInputStream manage the file’s data.

The programs in Java have dependencies based on he file structure and works well with manipulation of various files.

While many languages like Perl and other scripting languages have many utilities for parsing and Regex, Java’s strength rely in its cross-platform GUI’s and data manipulation with the use of buffers and files.

Java, especially J2EE, relies heavily on object serialization for when an object is saved to file or a database. And is heavily dependent on property files that define how the program is to run.

Page 60: Intro Java Rev010

Create a File

import java.io.*;public class CreateAFile { public static void main(String[] argv) throws IOException {// Ensure that a filename (or something) was given in argv[0] if (argv.length == 0) { System.err.println("Usage: CreateAFile filename"); System.exit(1); } // If arg is filled then create that file for (int i = 0; i< argv.length; i++) { new File(argv[i]).createNewFile( ); } }}

Page 61: Intro Java Rev010

List a Directory with “ls”

The File class can also be used for directory calls:// List the Directory "ls"public class ls { public static void main(String argh_my_aching_fingers[]) { String[] dir = new java.io.File(".").list( ); // Get list of names java.util.Arrays.sort(dir); // Sort it (see Recipe 7.8) for (int i=0; i<dir.length; i++) System.out.println(dir[i]); // Print the list }} Running “ls” will print the directory.

Page 62: Intro Java Rev010

Open a File

import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;

public class FileReader {public static void main(String[] args) {try{

Scanner text = new Scanner( new File( "Test.txt" ) );

}catch(FileNotFoundException ex){System.out.println("Error: "

+ex.getMessage());}

}}

Page 63: Intro Java Rev010

Scanner and File

The File class is used to create File object that contains information about the open file.

The File object can return the permissions on the file, where it is located in the directory, if it is a directory or hidden file, compare the file to another file and even get the size of the file.

The Scanner object can read integers, floats, doubles, lines and strings out of the file. The delimiter is normally a white space but can be changed to any character.

Regular expressions can also be used with the “java.util.regex.Matcher” class to

Page 64: Intro Java Rev010

Regular Expressions

Regular expressions is the process of matching a pattern in a string.

For example, the “.” matches any character, so the pattern “.at” matches can be used to match any three character string ending with "at", including "hat", "cat", and "bat".

Regular expressions can also be used with the “java.util.regex.Matcher” class, the Pattern class or even the string.

By comparing the patterns in a string, input can be validated to match proper input.

The following code snippet shows how to check a zip string so that it matches 5 digits, of course this string passes:

String zip = “80120”;if(zip.matches("\\d{5}") == false)

System.out.println("Error: zip code");

Page 65: Intro Java Rev010

Regular Expressions resources

http://www.regular-expressions.info/java.html

http://java.sun.com/docs/books/tutorial/essential/regex/

http://www.sitepoint.com/article/java-regex-api-explained/

http://www.regular-expressions.info/java.html

http://java.sun.com/docs/books/tutorial/essential/regex/

http://www.sitepoint.com/article/java-regex-api-explained/

Page 66: Intro Java Rev010

Sockets

Sockets are an Application Programming Interface (API) to perform network programming.

While there is SOA, URL and “java.nio” that abstracts sockets these days, sockets is a basic concept.

For sockets, there are client sockets that connect to a server through TCP or UDP, and server sockets that are listening for the connection.

A argument that is always required is the port number of the service, such as port 21 for FTP, and the client also requires the server IP address or host name to connect to he appropriate server.

Page 67: Intro Java Rev010

Client Socket

A client side socket needs to find the server and connect on s specific port, here is a ftp connection using the “java.net.Socket” class:

try {

Socket sock = new Socket(“www.state.co.us", 80);

} catch ( UnknownHostException e ) {

System.out.println("Can't find host.");

} catch ( IOException e ) {

System.out.println("Error connecting to host.");

}

Page 68: Intro Java Rev010

Server Socket

The Server socket is more complex because a multiple clients can connect to the server at once, and the server must “listen” for the client, then “accept” its connection and thread its work into “runnable” action.

Here’s some code that will “listen” on port 80, “accept” the client, and start the thread:

public class TinyHttpd { public static void main( String argv[] ) throws IOException

{ ServerSocket ss = new ServerSocket(80); while ( true ) new Thread( new

TinyHttpdConnection( ss.accept() ) ).start( ); }}

Page 69: Intro Java Rev010

Httpd (Http Server) continue

After we accept the client, we pass the socket to the thread:

class TinyHttpdConnection implements Runnable { Socket client; TinyHttpdConnection ( Socket client ) throws SocketException { this.client = client; } public void run( ) { try { BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream( ),

"8859_1" ) ); OutputStream out = client.getOutputStream( ); PrintWriter pout = new PrintWriter( new OutputStreamWriter(out, "8859_1"), true ); String request = in.readLine( ); System.out.println( "Request: "+request);

Page 70: Intro Java Rev010

Httpd continue

We are going to find a URL in the directory and pass it back to the browser:

Matcher get = Pattern.compile("GET /?(\\S*).*").matcher( request );

if ( get.matches( ) ) { request = get.group(1); if ( request.endsWith("/") || request.equals("") ) request = request + "index.html"; try { FileInputStream fis = new FileInputStream ( request ); byte [] data = new byte [ 64*1024 ]; for(int read; (read = fis.read( data )) > -1; ) out.write( data, 0, read ); out.flush( ); } catch ( FileNotFoundException e ) { pout.println( "404 Object Not Found" ); }

Page 71: Intro Java Rev010

Browsing Httpd

After creating a base “index.htm”, I placed it in the base directory where the java program was stored so that it may be called by Httpd:

Page 72: Intro Java Rev010

URL (Uniform Resource Locators)

The “socket” class was a lot of work to simply get a web connection on the client side.

All I really want to do is abstract the low level interaction and just pass a URL like a browser, so Java came up with the URL class.

Here is an example that will print the index.html from google:

try { URL url = new

URL("http://www.google.com/index.html"); BufferedReader bin = new BufferedReader (

new InputStreamReader( url.openStream( ) ));

String line; while ( (line = bin.readLine( )) != null )

System.out.println( line ); } catch (Exception e) { }

Page 73: Intro Java Rev010

Browsing becomes simplified

Many of the URL’s classes become more abstracted by framworks being built on top of frameworks.

Looking at SWTBrowser example from IBM, the “org.eclipse.swt.browser” abstracts most of the work.

The Standard Widget Toolkit (SWT) is GUI framework built by IBM for the Eclipse IDE.

Page 74: Intro Java Rev010

Browsing becomes simplified

public static void main(String[] args) {org.eclipse.swt.widgets.Display display = org.eclipse.swt.widgets.Display.getDefault();

SimpleSWTBrowser thisClass = new SimpleSWTBrowser();thisClass.createSShell();thisClass.sShell.open();while (!thisClass.sShell.isDisposed()) {if (!display.readAndDispatch())

display.sleep();}

display.dispose();}

//The URL is called in the createSShell code

Page 75: Intro Java Rev010

Browsing becomes simplified

Page 76: Intro Java Rev010

NIO (New I/O)

The “java.nio” package introduces new concepts to Input/Output (I/O).

In the previous cumbersome example of Httpd, a thread was created for every socket. With NIO, the concept now becomes a channel.

A channel is simply a pipe from the buffer to the I/O device, usually a socket or file.

The Buffer object is simply a fixed amount of data held in space. The buffer is the date, it may contain a string, integer, or XML data, but it is decoupled from the I/O device, like a socket.

The buffer deals with the data, there should be no concern for the device. The buffer has methods so that it can manipulate its data.

The channel is the conduit between the buffer and I/O device.

Page 77: Intro Java Rev010

Extensible Markup Language (XML)

XML is a specification for creating custom markup languages.

An example of a language that XML can create is Hypertext Markup Language (HTML) that is the language for programming browser code.

XML is very flexible because it uses tags to describe data elements:

<book>This is a book... </book>

The XML file is commonly use to transfer language elements over HTTP in the form of Web Services.

The XMML file must also contain the proper header information to state that the XML version and encoding scheme:

<?xml version="1.0" encoding="UTF-8"?>

There are several types of parsers for XML but the basic types are Document Object Model (DOM) and Simple API for XML (SAX).

Page 78: Intro Java Rev010

XML and Serialization

By using reflection mentioned earlier, the XMLEncoder class can write an object into XML format:

import java.io.*;import java.beans.XMLEncoder;public class WriteMe {public static void main(String[] args) throws IOException{MyData data = new MyData();data.setName("testXML");XMLEncoder e = new XMLEncoder( new BufferedOutputStream( new FileOutputStream("Test.xml")));e.writeObject(data);e.close();} }

Page 79: Intro Java Rev010

XML Bean

This Value Object, an object that only contains data, is considered a Bean:

/** Simple data class used as a Bean. */public class MyData{

public String name;public void setName(String name){

this.name = name;}public String getName(){

return name;}

}

Page 80: Intro Java Rev010

Now it is an XML object

<?xml version="1.0" encoding="UTF-8"?>

<java version="1.6.0_07" class="java.beans.XMLDecoder">

<object class="MyData">

<void property="name">

<string>testXML</string>

</void>

</object>

</java>

Page 81: Intro Java Rev010

SAX

SAX, http://www.saxproject.org/ , is a Simple API for XML.It basically opens the XML file with an XML reader, and

passes the file to a handler.The handler will traverse the XML file, parsing the tags

for specific input until it finishes with the file.

SAX, http://www.saxproject.org/ , is a Simple API for XML.It basically opens the XML file with an XML reader, and

passes the file to a handler.The handler will traverse the XML file, parsing the tags

for specific input until it finishes with the file.

Page 82: Intro Java Rev010

SAX

import java.io.IOException;import org.xml.sax.*;public class SAXParser{

public static void main(String[] args) throws Exception {new SAXParser(args);

}public SAXParser(String[] args) throws SAXException, IOException {

XMLReader parser = XMLReaderFactory.createXMLReader();

parser.setContentHandler(new MyDataHandler());parser.parse(args.length == 1 ? args[0] : "Test.xml");

}

Page 83: Intro Java Rev010

SAX (handler)

// Inner class provides DocumentHandlerclass MyDataHandler extends DefaultHandler {

boolean name = false; // Set to true when string tag is found

public void startElement(String nsURI, String localName,String rawName, Attributes attributes) throws

SAXException {if (rawName.equalsIgnoreCase("string"))

name = true;}public void characters(char[] ch, int start, int length) {if (name) { //Will print all name strings found

System.out.println("MyData name: " + new String(ch, start, length));

name = false;} } } }

Page 84: Intro Java Rev010

DOM

The Document Object Model (DOM) is the XML parsing technique used by most browsers.

The DOM parser uses a Document Type Definition file that defines the elements in the XML file that makes up the markup language.

The DocumentBuilder class is used that uses a resolveEntity () to import the DTD class. The DTD and DocumentBuilder will parse out the XML File into a Document class.

The Document class is a tree structure that contains the data.

Since the DocumentBuilder class will parse the file all at once, it requires higher overhead than serially parsing the file as SAX.

Page 85: Intro Java Rev010

ARRAYS, LOOPS AND COLLECTIONS

Page 86: Intro Java Rev010

Arrays, Loops and Collections

This section could easily be labeled “how do we move data in the Java program”

Arrays – is a bounded collection of the same data type.Loops – A loop continues the statements to execute until a

condition is met to tell the block of code to stop continuing.

Collections – Are a common set of Java utilities that use interfaces to define a generic collection of data types. This was similar to the various Standard Template Libraries (STL) of C++. Collections include Lists, Sets, Maps, and other dynamic data structures.

Page 87: Intro Java Rev010

Arrays

By bounded, an array is a fixed size that has to be defined.An Array can be single dimension or multi-dimension, but

all the data types must be the same.

Page 88: Intro Java Rev010

Arrays, the code

public class ArrayProgram {public static void main(String[] args){

String [] strArray = new String[3];strArray[0] = "One"; //Java starts at 0strArray[1] = "Two";strArray[2] = "Three";int [] [] intArray = new int[2][]; // 2 rowsintArray[0] = new int[3]; // three columns for row 0intArray[1] = new int[4]; // four columns for row 1int data = 1;for(int i1 = 0; i1 < intArray.length; i1++){ for(int i2 = 0; i2 < intArray[i1].length; i2++){

intArray[i1][i2] = data++; }}

Page 89: Intro Java Rev010

Arrays, the code

for(int i1 = 0; i1 < intArray.length; i1++){System.out.println("Output for Row [" +i1 +"]");for(int i2 = 0; i2 < intArray[i1].length; i2++){

System.out.printf("%d ", intArray[i1][i2]);}System.out.println();

} }}

Output: Output for Row [0] 1 2 3 Output for Row [1] 4 5 6 7

Page 90: Intro Java Rev010

Conditionals

Before understanding loops, it is important to understand conditionals , or control statements.

A conditional changes the path of execution of code based on a condition being met or not.

A conditional is based on he “boolean” type “true” which is the same as a “1” value and “false” which is the same as “0”.

The basic conditional is the “if” statement, simply put, if this is true then do this statement else do something else:

if(true)System.out.println("Do the right thing");

elseSystem.out.println("Do soemthing else");

Page 91: Intro Java Rev010

if, else if, else

If statements can be nested within each other, and added until it is almost unreadable. Take care to structure the programming style so that you can read it later:

public static void main(String[] args) {boolean bDoThis = true, bAlsoThis = true;boolean bNotThat = false;if(bNotThat){System.out.println("Don't do");

}else if(bDoThis){System.out.print("This will work");if(bAlsoThis)

System.out.print(" and this.");}else{

System.out.println("Not this");}} The output is “This will work and this.”

Page 92: Intro Java Rev010

&& and || operators

Some if statements require multiple conditions to be met or a single condition out of multiple selections.

When all conditions have to be met, the && (and) operator is used. It states that this and that must be met.

When a single condition has to be met out of multiple selections, the || operator is used stating this or that must be met.

Code snippet:String myString = "good";String myString2 = "good";if(myString2.length() > 0 || myString.length() > 0)

System.out.println("A String is empty");else if(myString.equals("good") && myString2.equals("good"))

System.out.println("Both are good");

Page 93: Intro Java Rev010

switch

To help keep the code clean, the switch statement can be used. The switch statement executes paths based on labels. A label for the switch statement is a primitive type variable, such

as a byte, character, integer, or short. A properly formatted switch statement requires a default label in

case non of the other conditions are met.

Page 94: Intro Java Rev010

Switch demo

class SwitchDemo {public static void main(String[] args) {

int month = 8;switch (month) {

case 1: System.out.println("January"); break;case 2: System.out.println("February"); break;case 3: System.out.println("March"); break;case 4: System.out.println("April"); break;case 5: System.out.println("May"); break;case 6: System.out.println("June"); break;case 7: System.out.println("July"); break;case 8: System.out.println("August"); break;case 9: System.out.println("September"); break;case 10: System.out.println("October"); break;case 11: System.out.println("November"); break;case 12: System.out.println("December"); break;default: System.out.println("Invalid

month.");break; }}}

Page 95: Intro Java Rev010

The “for” loop

for(int i1 = 0; i1 < intArray.length; i1++)System.out.println("Output for Row [" +i1 +"]");

This “for” has three parts, initialization, the conditional, and the execution.

Following the “for loop” is the block of execution that will be executed until the condition is false.

In the statement “for(int i1 = 0” the interger “i1” is initialized to 0 for the execution of the loop.

The “i1 < intArray.length;” will be true as long as “i1” is lower than the length of the intArray and as long it is true the loop continues.

The “i1” is incremented by the “i1++)” statement after the completion of each loop.

Page 96: Intro Java Rev010

The “for each” loop

double[] ar = {1.2, 3.0, 0.8};int sum = 0;for (double d : ar) { // d gets successively each value in ar. sum += d;}Only access. Elements can not be assigned to, eg, not to

increment each element in a collection. Only single structure. It's not possible to traverse two

structures at once, eg, to compare two arrays. Only single element. Use only for single element access,

eg, not to compare successive elements. Only forward. It's possible to iterate only forward by

single steps. At least Java 5. Don't use it if you need compatibility with

versions before Java 5.

Page 97: Intro Java Rev010

The “while” loop

The “while” loop is a simpler loop that will only execute it’s block of instructions until a condition is no longer met.

A “while” loop could easily replace a “for” loop with less built-in statements:

int i1 = 0;while(i1 < intArray.length){System.out.println("Output for Row [" +i1 +"]");i1++;Just like a “for” loop can replace the simple pieces of a

while loop:boolean condition = true;while(condition)

could be rewritten to : for(boolean condition = true; condition; )

Page 98: Intro Java Rev010

Let’s “break” and “continue

The continue keyword can be used for the for, while, and do-while loops.

Its purpose is to stop the current iteration of the loop and start the next iteration of the loop.

The continue statement can be labeled or unlabeled. The break statement breaks out of the loop completely.

Page 99: Intro Java Rev010

“break” and “continue example

public static void main(String[] args) {boolean bFirstLoop = true, boolean bBreakMe = true,

bContinue = true;while(bFirstLoop){

System.out.println("While Loop");if(bBreakMe)

break; // Prints only one “While Loop”}for(int i = 0; i < 3;i++){

if(bContinue){bContinue = false;continue;

}System.out.println("For Loop"); //Prints twice, skips

first time}

}

Page 100: Intro Java Rev010

Benefits of Collections

A collection is simply a organized group of objects or data types.

Their benefit’s include:

1)Reducing the program effort by providing the plumbing already.

2)Increase the program speed and quality by using methods that have been proven in the industry.

3)Allows interoperability among unrelated API’s by using the same interfaces.

4)Fosters software reuse, reduces effort and the learning curve by using frameworks that have already been created.

Examples of collections include Vector, Lists, HashTables, Sets and Maps.

Page 101: Intro Java Rev010

Linked List

The issue with using the basic array data structure “array [ ]” is that the bounds of the array have to be known when the array is created “= new int[13]”.

It is difficult to know the size of a collection, say getting a database entry or reading a file. The program may need to grow with the size of the data.

For this reason linked lists are often used. A link list uses a link to index the list to walk down the

data:

Page 102: Intro Java Rev010

Linked List, some code

import java.util.LinkedList;public class ListProgram { public static void main(String[] args) {

LinkedList < String> strList = new LinkedList <String>();

strList.add("One");strList.add("Two");strList.add("Three");System.out.print("Output -> The Linked List

vaues =");for(int i1 = 0; i1 < strList.size(); i1++)

System.out.printf("%s ", strList.get(i1));

} }Output -> The Linked List vaues =One Two Three

Page 103: Intro Java Rev010

Labs

1) Build a Hello World.2) Create a Loop with a conditional and array.3) Create a program with a Collection.4) Create a file.