Your SlideShare is downloading. ×

Intro Java Rev010

992
views

Published on

Published in: Technology, News & Politics

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
992
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
15
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. JAVA ESSENTIALS BY RICH HELTON (SUN CERTIFIED (SC) JAVA PROGRAMMER, SC JAVA DEVELOPER, SC ENTERPRISE ARCHITECT) January 2009
  • 2. 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).
  • 3. 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.
  • 4. Java, the history … Version Year New Features 1.0 1996 1.1 1997 Inner classes 1.2 1998 Swing, Collections 1.3 2000 Performance enhancements 1.4 2002 Assertions, XML 5 2004 Generic classes, enhanced for loop, auto-boxing, enumerations 6 2006 Library improvements
  • 5. My First Java Program… public class MyFirstJavaProgram { // Start the program public static void main(String[] args){ if(args.length >0){ // If argument print name String myName = (String) args[0]; System.out.println("Hello " +myName); }else{ // Else print System.out.println("Hello there"); } } }
  • 6. Find it your java program…
    • At the command prompt :
  • 7. 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 :
  • 8. Compile…
    • At the command prompt, run the java compiler “javac”:
  • 9. Run the program…
    • At the command prompt, run the java program without the argument, “java” runs the program:
  • 10. LET’S BREAK DOWN THE PROGRAM
  • 11. Components of this application…
    • Comments
    • Reserved words
    • Modifiers
    • Statements
    • Blocks
    • Classes
    • Methods
    • The main method
  • 12. 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
    • */
  • 13. 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.
  • 14. Sample Reserved Words public class MyFirstJavaProgram { // Start the program public static void main(String[] args){ if (args.length >0){ // If argument print name String myName = (String) args[0]; System.out.println("Hello " +myName); } else { // Else print System.out.println("Hello there"); } } }
  • 15. 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.
  • 16. 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.
  • 17. Sample Modifiers public class MyFirstJavaProgram { // Start the program public static void main(String[] args){ if(args.length >0){ // If argument print name String myName = (String) args[0]; System.out.println("Hello " +myName); }else{ // Else print System.out.println("Hello there"); } } }
  • 18. 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);
  • 19. 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.
  • 20. Sample Block
  • 21. 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.
  • 22. 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.
  • 23. 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.
  • 24. A BRIEF INTRODUCTION INTO OBJECT ORIENTED PROGRAMMING (OOP)
  • 25. 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.
  • 26. 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.
  • 27. 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”.
  • 28. 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);
  • 29. 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.
  • 30. 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.
  • 31. 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.
    • }
  • 32. 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.
  • 33. 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).
  • 34. 2 nd 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";
    • }
    • //Setter
    • void setName(String myName){
    • this.myName = myName;
    • }
    • //Getter
    • String getName(){
    • return this.myName;
    • }
    • }
  • 35. 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.
  • 36. 2 nd 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.
  • 37. 2 nd 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
    • }
  • 38. 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.
  • 39. 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;
    • // Constructor
    • MySecondObject(){
    • myComment = "No Argument";
    • }
    • //Setter
    • void setComment(String myComment){
    • this.myComment = myComment ;
    • }
    • //Getter
    • String getComment(){
    • return this.myComment;
    • }
    • }
  • 40. 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 parent
    • myObj.setName(args[0]);
    • // From child
    • myObj.setComment("Argument found");
    • }
    • System.out.println("Hello " + myObj.getName());
    • } // End Main
    • }
  • 41. 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.
  • 42. 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 name
    • void printName(){
    • System. out.println("MyFirstObject's name " + super.myName);
    • }
  • 43. 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(); } }
  • 44. Reflection (finding my fields/methods) class WhoAmI{ String test1 =&quot;I think&quot;; String test2 = &quot;Therefore I am&quot;; void CanYouSeeMe(){} void WhoAreYou(){ System. out.println(&quot;WhoAmI:&quot; +this.getClass().getName()); Method [] methods = this.getClass().getDeclaredMethods(); Field [] fields = this.getClass().getDeclaredFields(); for(int i =0; i < methods.length;i++) System. out.println(&quot;Method:&quot; +methods[i].getName()); for(int i =0; i < fields.length;i++) System. out.println(&quot;Field:&quot; +fields[i].getName()); }
  • 45. 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:WhoAmI
    • Method:WhoAreYou
    • Method:CanYouSeeMe
    • Field:test1
    • Field:test2
  • 46. 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.
  • 47. 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;
  • 48. 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;”
  • 49. 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.
  • 50. JAR Example
  • 51. 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(&quot;Classpath:&quot; + System.getProperty(&quot;java.class.path&quot;));
    • System. out.println(&quot;Java Version:&quot; + System.getProperty(&quot;java.version&quot;));
    • System. out.println(&quot;Java Home:&quot; + System.getProperty(&quot;java.home&quot;));
    • System. out.println(&quot;Operating System:&quot; + System.getProperty(&quot;os.name&quot;));
    • System. out.println(&quot;User's Home:&quot; + System.getProperty(&quot;user.home&quot;));
    • System. setProperty(&quot;user.home&quot;, &quot;C:ocuments and Settings&quot;);
    • System. out.println(&quot;User's Home:&quot; + System.getProperty(&quot;user.home&quot;));
    • }
    • }
  • 52. Java Properties
    • Notice that the “user.home” was changed by the program:
    • Java Version:1.6.0_07
    • Java Home:C:Program FilesJavajre1.6.0_07
    • Operating System:Windows XP
    • User's Home:C:Documents and Settingsqnwa08
    • User's Home:C:Documents and Settings
  • 53. 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.
  • 54. INPUT/OUTPUT (I/O)
  • 55. 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 = &quot;You cannot change&quot;;
    • test = test.toLowerCase();
    • System.out.println(test);
  • 56. 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(&quot;You cannot change&quot;);
    • test.reverse();
    • System.out.println(test);
  • 57. 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 =&quot;You&quot; + &quot; cannot &quot; + &quot;change me&quot;;
    • int len = &quot;You cannot change me&quot;.length();
    • test = &quot; You &quot;;
    • test += &quot;cannot &quot;;
    • test += &quot;change me&quot;;
  • 58. 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 = &quot;Java,is,Cool&quot;;
    • StringTokenizer st = new StringTokenizer(str, &quot;,&quot;);
    • while (st.hasMoreTokens()) {
    • System.out.print(st.nextToken()+ &quot; &quot;);
    • The Output is : Java is Cool
  • 59. 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.
  • 60. 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(&quot;Usage: CreateAFile filename&quot;); System.exit(1); } // If arg is filled then create that file for (int i = 0; i< argv.length; i++) { new File(argv[i]).createNewFile( ); } } }
  • 61. List a Directory with “ls”
    • The File class can also be used for directory calls:
    • // List the Directory &quot; ls&quot;
    • public class ls {
    • public static void main(String argh_my_aching_fingers[]) {
    • String[] dir = new java.io.File(&quot;.&quot;).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.
  • 62. 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( &quot;Test.txt&quot; ) ); }catch(FileNotFoundException ex){ System. out.println(&quot;Error: &quot; +ex.getMessage()); } } }
  • 63. 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
  • 64. 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 &quot;at&quot;, including &quot; hat &quot;, &quot; cat &quot;, and &quot; bat &quot;.
    • 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(&quot;{5}&quot;) == false)
    • System.out.println(&quot;Error: zip code&quot;);
  • 65. 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/
  • 66. 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.
  • 67. 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&quot;, 80);
    • } catch ( UnknownHostException e ) {
    • System.out.println(&quot;Can't find host.&quot;);
    • } catch ( IOException e ) {
    • System.out.println(&quot;Error connecting to host.&quot;);
    • }
  • 68. 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( );
    • }
    • }
  • 69. 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( ), &quot;8859_1&quot; ) );
    • OutputStream out = client.getOutputStream( );
    • PrintWriter pout = new PrintWriter(
    • new OutputStreamWriter(out, &quot;8859_1&quot;), true );
    • String request = in.readLine( );
    • System. out.println( &quot;Request: &quot;+request);
  • 70. Httpd continue
    • We are going to find a URL in the directory and pass it back to the browser:
    • Matcher get = Pattern. compile(&quot;GET /?(*).*&quot;).matcher( request );
    • if ( get.matches( ) ) {
    • request = get.group(1);
    • if ( request.endsWith(&quot;/&quot;) || request.equals(&quot;&quot;) )
    • request = request + &quot;index.html&quot;;
    • 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( &quot;404 Object Not Found&quot; ); }
  • 71. 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:
  • 72. 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(&quot;http://www.google.com/index.html&quot;);
    • BufferedReader bin = new BufferedReader (
    • new InputStreamReader( url.openStream( ) ));
    • String line;
    • while ( (line = bin.readLine( )) != null )
    • System. out.println( line );
    • } catch (Exception e) { }
  • 73. 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.
  • 74. 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
  • 75. Browsing becomes simplified
  • 76. 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.
  • 77. 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=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
    • There are several types of parsers for XML but the basic types are Document Object Model (DOM) and Simple API for XML (SAX).
  • 78. 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(&quot;testXML&quot;);
    • XMLEncoder e = new XMLEncoder(
    • new BufferedOutputStream(
    • new FileOutputStream(&quot;Test.xml&quot;)));
    • e.writeObject(data);
    • e.close();
    • } }
  • 79. 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;
    • }
    • }
  • 80. Now it is an XML object <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <java version=&quot;1.6.0_07&quot; class=&quot;java.beans.XMLDecoder&quot;> <object class=&quot;MyData&quot;> <void property=&quot;name&quot;> <string>testXML</string> </void> </object> </java>
  • 81. 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.
  • 82. 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] : &quot;Test.xml&quot;); }
  • 83. SAX (handler) // Inner class provides DocumentHandler class 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(&quot;string&quot;)) name = true; } public void characters(char[] ch, int start, int length) { if (name) { //Will print all name strings found System. out.println(&quot;MyData name: &quot; + new String(ch, start, length)); name = false; } } } }
  • 84. 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.
  • 85. ARRAYS, LOOPS AND COLLECTIONS
  • 86. 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.
  • 87. 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.
  • 88. Arrays, the code public class ArrayProgram { public static void main(String[] args){ String [] strArray = new String[3]; strArray[0] = &quot;One&quot;; //Java starts at 0 strArray[1] = &quot;Two&quot;; strArray[2] = &quot;Three&quot;; int [] [] intArray = new int[2][]; // 2 rows intArray[0] = new int[3]; // three columns for row 0 intArray[1] = new int[4]; // four columns for row 1 int data = 1; for(int i1 = 0; i1 < intArray.length; i1++){ for(int i2 = 0; i2 < intArray[i1].length; i2++){ intArray[i1][i2] = data++; } }
  • 89. Arrays, the code
    • for(int i1 = 0; i1 < intArray.length; i1++){
    • System. out.println(&quot;Output for Row [&quot; +i1 +&quot;]&quot;);
    • for(int i2 = 0; i2 < intArray[i1].length; i2++){
    • System. out.printf(&quot;%d &quot;, intArray[i1][i2]);
    • }
    • System. out.println();
    • }
    • }
    • }
    • Output:
    • Output for Row [0]
    • 1 2 3
    • Output for Row [1]
    • 4 5 6 7
  • 90. 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(&quot;Do the right thing&quot;);
    • else
    • System.out.println(&quot;Do soemthing else&quot;);
  • 91. 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(&quot;Don't do&quot;);
    • }else if(bDoThis){
    • System.out.print(&quot;This will work&quot;);
    • if(bAlsoThis)
    • System.out.print(&quot; and this.&quot;);
    • }else{
    • System.out.println(&quot;Not this&quot;);}}
    • The output is “This will work and this.”
  • 92. && 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 = &quot;good&quot;;
    • String myString2 = &quot;good&quot;;
    • if(myString2.length() > 0 || myString.length() > 0)
    • System.out.println(&quot;A String is empty&quot;);
    • else if(myString.equals(&quot;good&quot;) && myString2.equals(&quot;good&quot;))
    • System.out.println(&quot;Both are good&quot;);
  • 93. 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.
  • 94. Switch demo class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println(&quot;January&quot;); break; case 2: System.out.println(&quot;February&quot;); break; case 3: System.out.println(&quot;March&quot;); break; case 4: System.out.println(&quot;April&quot;); break; case 5: System.out.println(&quot;May&quot;); break; case 6: System.out.println(&quot;June&quot;); break; case 7: System.out.println(&quot;July&quot;); break; case 8: System.out.println(&quot;August&quot;); break; case 9: System.out.println(&quot;September&quot;); break; case 10: System.out.println(&quot;October&quot;); break; case 11: System.out.println(&quot;November&quot;); break; case 12: System.out.println(&quot;December&quot;); break; default: System.out.println(&quot;Invalid month.&quot;);break; }}}
  • 95. The “for” loop
    • for(int i1 = 0; i1 < intArray.length; i1++)
    • System.out.println(&quot;Output for Row [&quot; +i1 +&quot;]&quot;);
    • 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.
  • 96. 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.
  • 97. 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(&quot;Output for Row [&quot; +i1 +&quot;]&quot;);
    • 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; )
  • 98. 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.
  • 99. “ break” and “continue example public static void main(String[] args) { boolean bFirstLoop = true, boolean bBreakMe = true, bContinue = true; while(bFirstLoop){ System.out.println(&quot;While Loop&quot;); if(bBreakMe) break; // Prints only one “While Loop” } for(int i = 0; i < 3;i++){ if(bContinue){ bContinue = false; continue; } System.out.println(&quot;For Loop&quot;); //Prints twice, skips first time } }
  • 100. Benefits of Collections
    • A collection is simply a organized group of objects or data types.
    • Their benefit’s include:
    • Reducing the program effort by providing the plumbing already.
    • Increase the program speed and quality by using methods that have been proven in the industry.
    • Allows interoperability among unrelated API’s by using the same interfaces.
    • 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.
  • 101. 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:
  • 102. 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(&quot;One&quot;); strList.add(&quot;Two&quot;); strList.add(&quot;Three&quot;); System. out.print(&quot;Output -> The Linked List vaues =&quot;); for(int i1 = 0; i1 < strList.size(); i1++) System. out.printf(&quot;%s &quot;, strList.get(i1)); } } Output -> The Linked List vaues =One Two Three
  • 103. Labs
    • Build a Hello World.
    • Create a Loop with a conditional and array.
    • Create a program with a Collection.
    • Create a file.

×