Intro Java Rev010


Published on

Published in: Technology, News & Politics
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Intro Java Rev010

  2. 2. Java, the beginning … <ul><li>During the 1990's, frameworks and memory usage was a common issue with C and C++. </li></ul><ul><li>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. </li></ul><ul><li>It was not uncommon to have a framework for parsing, and a different one for networks. </li></ul><ul><li>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. </li></ul><ul><li>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). </li></ul>
  3. 3. Java, the beginning … <ul><li>Java provided a common framework as part of the language to handle strings, networks, and extended functions. </li></ul><ul><li>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. </li></ul><ul><li>Java also provided Object Oriented Programming where the framework and pieces were used as objects to abstract the details. </li></ul><ul><li>The various pieces of objects could be combined into new combinations, normally known as design patterns, to produce new functionality. </li></ul>
  4. 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. 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(&quot;Hello &quot; +myName); }else{ // Else print System.out.println(&quot;Hello there&quot;); } } }
  6. 6. Find it your java program… <ul><li>At the command prompt : </li></ul>
  7. 7. Find the compiler… <ul><li>At the command prompt, check to make sure that the JDK is set for compiling : </li></ul><ul><li>At the command prompt, the JDK is set in the environment for compiling : </li></ul>
  8. 8. Compile… <ul><li>At the command prompt, run the java compiler “javac”: </li></ul>
  9. 9. Run the program… <ul><li>At the command prompt, run the java program without the argument, “java” runs the program: </li></ul>
  11. 11. Components of this application… <ul><li>Comments </li></ul><ul><li>Reserved words </li></ul><ul><li>Modifiers </li></ul><ul><li>Statements </li></ul><ul><li>Blocks </li></ul><ul><li>Classes </li></ul><ul><li>Methods </li></ul><ul><li>The main method </li></ul>
  12. 12. Comments <ul><li>Comments are used to communicate the purpose of parts of the program in the code. </li></ul><ul><li>Comments are not executed as part of the code and are ignored by the compiler. </li></ul><ul><li>Using the (//) double slashes will tell the compiler to ignore the entire line. </li></ul><ul><li>Using the (/*) slash star will start the compiler to ignore the comment until it meets the ending slash star (*/). </li></ul><ul><li>Here are the two types of comments: </li></ul><ul><li>// Start the program, single line comment </li></ul><ul><li>/* Start the program, </li></ul><ul><li> multiple line comment </li></ul><ul><li> */ </li></ul>
  13. 13. Reserved Words <ul><li>Reserved words, or keywords, are words with special meaning that define how the program should behave in the compiler. </li></ul><ul><li>These are words will explain to the compiler how to construct the program. </li></ul><ul><li>Being reserved to the compiler, these words cannot be duplicated anywhere else in the code as class names, variable names, or method names. </li></ul><ul><li>Words in the program, such as “public class” tells the compiler to construct the class with scope of “public” protection. </li></ul><ul><li>Java keywords are case sensitive, so care must be taken in ensuring the case is consistent with the language specification. </li></ul>
  14. 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(&quot;Hello &quot; +myName); } else { // Else print System.out.println(&quot;Hello there&quot;); } } }
  15. 15. Modifiers, or Access Modifiers <ul><li>Modifiers define the protection and global or local scope of a class, method or variable. </li></ul><ul><li>There are modifiers for controlling access to a class, method, or variable: public, protected, and private </li></ul><ul><li>The static modifier can be used for defining a one of a kind global class, method or variable. </li></ul><ul><li>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. </li></ul><ul><li>The abstract modifier is used for defining classes and methods without creating the instance of the object. It forces rules on classes. </li></ul><ul><li>The synchronized and volatile modifiers, which are used for threads. </li></ul>
  16. 16. Public, Protected and Private <ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul>
  17. 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(&quot;Hello &quot; +myName); }else{ // Else print System.out.println(&quot;Hello there&quot;); } } }
  18. 18. Statements <ul><li>A statement is line for a singe unit of work. </li></ul><ul><li>A line in Java is ended with ( ; ) semicolon. </li></ul><ul><li>Sample statements from the “ MyFirstJavaProgram”: </li></ul><ul><li>String myName = (String) args[0]; </li></ul><ul><li>System.out.println(&quot;Hello &quot; +myName); </li></ul>
  19. 19. Blocks <ul><li>A block is a group of actions that is normally defined in a class as the higher level made up of multiple functions. </li></ul><ul><li>A block is started with the ( { ) opening brace and ends with the ( } ) closing brace. </li></ul>
  20. 20. Sample Block
  21. 21. Main method <ul><li>Every Java program must have a “main” method. </li></ul><ul><li>There is only one “main” method in every Java program. </li></ul><ul><li>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. </li></ul><ul><li>In the previous slide, the “Method block” of the “main” method is the execution of the program itself. </li></ul>
  22. 22. Main method <ul><li>Every Java program must have a “main” method. </li></ul><ul><li>There is only one “main” method in every Java program. </li></ul><ul><li>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. </li></ul><ul><li>In the previous slide, the “Method block” of the “main” method is the execution of the program itself. </li></ul>
  23. 23. What is a class? <ul><li>A class is a definition of a group of methods, variables, state and behavior. </li></ul><ul><li>In the sample, the class is MyFirstProgram. </li></ul><ul><li>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. </li></ul><ul><li>The idea of a class is that is can define a car, a catalog, and another group of a construct. </li></ul><ul><li>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. </li></ul><ul><li>When a class is created and started, called instatiation, it becomes an object. A class can create many objects. </li></ul>
  25. 25. A brief introduction to OOP <ul><li>Learning Object Oriented Programming is as easy as PIE. </li></ul><ul><li>PIE stands for Polymorphism, Inheritance and Encapsulation. </li></ul><ul><li>These PIE characteristics provide common properties like re-use of pieces, hiding of internal data, and propagating characteristics of objects into other objects. </li></ul><ul><li>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. </li></ul><ul><li>Using this fluid style of programming, relational tables can be defined and created by simply defining the initial Business Object. </li></ul><ul><li>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. </li></ul>
  26. 26. Polymorphism <ul><li>Polymorphism started a term in biology for how different types of species have the same generic traits. </li></ul><ul><li>It states that the same species may morph, having different qualities, in the same habitat. </li></ul><ul><li>For instance, the lady bug may morph into red spots or black spots in the same environment. </li></ul><ul><li>The commonality is that the two bugs are still lady bugs, but have different traits like spot colors. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul>
  27. 27. Polymorphism <ul><li>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. </li></ul><ul><li>Let’s use an example, if we have a “Toyota” truck and “Ford” truck created with it’s parent class “Truck”. </li></ul>
  28. 28. Polymorphism, continuing… <ul><li>Now, let’s create a program called “Midas Touch” that handles the Truck objects and rotates their tires. </li></ul><ul><li>class public MidasTouch{ </li></ul><ul><li>Truck myTruck = new (Truck) Toyota (); </li></ul><ul><li>} </li></ul><ul><li>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. </li></ul><ul><li>… rotateTires(myTruck); </li></ul>
  29. 29. Inheritance <ul><li>Inheritance has to do more with genealogy and parentage. </li></ul><ul><li>This concept is to understand an objects behavior and traits by its inherited lineage. </li></ul><ul><li>A “child” class has a “parent” class that gave it many default properties. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul>
  30. 30. Inheritance <ul><li>In the picture: </li></ul><ul><li>The Toyota and Ford are derived, or child classes, from their parent “Truck” </li></ul><ul><li>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. </li></ul><ul><li>These Truck parent may have passed on to Toyota and Ford that they had an engine, 4 tires, a windshield, gas tank, brakes, etc. </li></ul>
  31. 31. Inheritance, continuing… <ul><li>Now, let’s use create a class from the parent class. </li></ul><ul><li>class public Truck { </li></ul><ul><li>Brakes myBrakes; </li></ul><ul><li>Engine myEngine; </li></ul><ul><li>Windsheild myWindSheild; </li></ul><ul><li>} </li></ul><ul><li>class public Toyota extends Truck{ </li></ul><ul><li>// Already has myBrakes, myEngine, myWindsheild defined. </li></ul><ul><li>} </li></ul>
  32. 32. Encapsulation <ul><li>Encapsulation is also referred to as data hiding or information hiding. </li></ul><ul><li>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. </li></ul><ul><li>Many objects may use a constructor to pass information into the object that it cannot retrieve without using a “getter( )” method. </li></ul><ul><li>For example, I could create a “Ford Truck” object, and it will have many properties like color, bed type, bin number, etc. </li></ul><ul><li>It will also have embedded objects like tires, windshields, radio, seats, etc. </li></ul><ul><li>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. </li></ul>
  33. 33. Putting it all together <ul><li>OOP introduced a new way of developing programs. </li></ul><ul><li>Before OOP, programming was very procedural and structural. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>What became important in Object Oriented Design, is now the pieces of the program was merely a collection of objects. </li></ul><ul><li>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. </li></ul><ul><li>Many of these properties were later even entered into property files, and text messages which gave birth to Service-Oriented Architecture (SOA). </li></ul>
  34. 34. 2 nd Java Sample Program with an object <ul><li>Let’s create an class from the first program, and call it MyFirstObject: </li></ul><ul><li>class MyFirstObject{ </li></ul><ul><li>String myName; </li></ul><ul><li>MyFirstObject(){// Constructor </li></ul><ul><li>myName = &quot;there&quot;; </li></ul><ul><li>} </li></ul><ul><li>//Setter </li></ul><ul><li>void setName(String myName){ </li></ul><ul><li>this.myName = myName; </li></ul><ul><li>} </li></ul><ul><li>//Getter </li></ul><ul><li>String getName(){ </li></ul><ul><li>return this.myName; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  35. 35. Some new terms <ul><li>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. </li></ul><ul><li>The Constructor is the method used to create the object. There could be multiple constructors, taking in different arguments as they “overload” their methods. </li></ul><ul><li>Overloading is when a method with the same name, but a different argument, is called based in it’s argument. </li></ul><ul><li>Also, introduced is the “ this ” pointer, or keyword, used in Java reflection. </li></ul><ul><li>“ this ” allows an object to look into the current instance of itself. </li></ul><ul><li>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. </li></ul>
  36. 36. 2 nd Java Program object creation <ul><li>In the code, there must always be one and only one “main” method that starts the execution. </li></ul><ul><li>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. </li></ul><ul><li>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”. </li></ul><ul><li>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. </li></ul>
  37. 37. 2 nd Java Program object creation <ul><li>Always remember that an object is never created, or instantiated, unless the “new” keyword is used. Let’s create the object: </li></ul><ul><li>public class MySecondJavaProgram { </li></ul><ul><li>public static void main(String[] args){ </li></ul><ul><li>MyFirstObject myObj = new MyFirstObject(); </li></ul><ul><li>if(args.length >0){ // If argument print name </li></ul><ul><li>myObj.setName(args[0]); </li></ul><ul><li>} </li></ul><ul><li>System. out.println(&quot;Hello &quot; + myObj.getName()); </li></ul><ul><li>} // End Main </li></ul><ul><li>} </li></ul>
  38. 38. What happened <ul><li>From this program, “MySecondJavaProgram”, we were able to create an object with the “new” keyword. </li></ul><ul><li>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. </li></ul><ul><li>A main purpose of OOP is reusability. </li></ul><ul><li>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. </li></ul>
  39. 39. Extending functionality <ul><li>Let’s extend the functionality of the first object, with the “extend” keyword, and create a child class: </li></ul><ul><li>class MySecondObject extends MyFirstObject{ </li></ul><ul><li>String myComment; </li></ul><ul><li>// Constructor </li></ul><ul><li>MySecondObject(){ </li></ul><ul><li> myComment = &quot;No Argument&quot;; </li></ul><ul><li>} </li></ul><ul><li>//Setter </li></ul><ul><li>void setComment(String myComment){ </li></ul><ul><li>this.myComment = myComment ; </li></ul><ul><li>} </li></ul><ul><li>//Getter </li></ul><ul><li>String getComment(){ </li></ul><ul><li>return this.myComment; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  40. 40. Extending functionality <ul><li>The program will create 2 objects now, the child object “MySecondObject” will create a “MyFirstObject” when created and use it’s functionality: </li></ul><ul><li>public class MyThirdJavaProgram { </li></ul><ul><li>public static void main(String[] args){ </li></ul><ul><li>MySecondObject myObj = new MySecondObject(); </li></ul><ul><li>if(args.length >0){ // If argument print name </li></ul><ul><li>// From parent </li></ul><ul><li>myObj.setName(args[0]); </li></ul><ul><li>// From child </li></ul><ul><li>myObj.setComment(&quot;Argument found&quot;); </li></ul><ul><li>} </li></ul><ul><li>System.out.println(&quot;Hello &quot; + myObj.getName()); </li></ul><ul><li>} // End Main </li></ul><ul><li>} </li></ul>
  41. 41. Extending functionality <ul><li>By extending functionality in a new object, I was able to add methods and variables without changing the initial code and how it works. </li></ul><ul><li>This becomes monumental when creating frameworks because now libraries can be extended without changing original functionality. </li></ul><ul><li>A new concept that can be introduced here is called “Overrriding”. </li></ul><ul><li>Overriding methods occurs when the method of the child class is used instead of the parent. </li></ul><ul><li>Since the parent, or super class, had a “setName” method, and the child did not, the parent’s method was used. </li></ul><ul><li>The child could “override” the parent’s “setName” method by simply having its own. </li></ul>
  42. 42. SUPER <ul><li>So far, we have discussed that when a child object is created, the parent object is also created and the child inherits their attributes. </li></ul><ul><li>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: </li></ul><ul><li>//Print the name </li></ul><ul><li>void printName(){ </li></ul><ul><li>System. out.println(&quot;MyFirstObject's name &quot; + super.myName); </li></ul><ul><li>} </li></ul>
  43. 43. Reflection <ul><li>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. </li></ul><ul><li>Reflection comes in handy when serializing objects (saving to disk) and writing the objects variables and methods into XML. </li></ul><ul><li>The Simple API for XML (SAX) parser using reflection to develop its data definitions and types. </li></ul><ul><li>Let’s start the code: </li></ul><ul><li>import java.lang.reflect.*; </li></ul><ul><li>public class Reflection1{ </li></ul><ul><li>public static void main(String[] args) { </li></ul><ul><li>WhoAmI whoami = new WhoAmI(); </li></ul><ul><li>whoami.WhoAreYou(); } } </li></ul>
  44. 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. 45. Reflection <ul><li>The code produced its fields and methods. </li></ul><ul><li>After collecting this information, it could easily be placed on the network, through XML or serialized to show what is available. </li></ul><ul><li>The output: </li></ul><ul><li>WhoAmI:WhoAmI </li></ul><ul><li>Method:WhoAreYou </li></ul><ul><li>Method:CanYouSeeMe </li></ul><ul><li>Field:test1 </li></ul><ul><li>Field:test2 </li></ul>
  46. 46. Abstract (Must Do) <ul><li>Not only can a child inherit from their parent, but a child can also be told the interface that they must produce. </li></ul><ul><li>This technique is an “interface” which is basically a parent that can “Do as I say and not as I do”. </li></ul><ul><li>Here’s an example interface that will force the child class to create the “setName” and “getName” methods: </li></ul><ul><li>interface MustDo{ </li></ul><ul><li>public abstract void setComment(String myComment); </li></ul><ul><li>abstract String getComment(); </li></ul><ul><li>} </li></ul><ul><li>class MySecondObject extends MyFirstObject implements MustDo{ </li></ul><ul><li>The second object will inherit from the first, but it “has to” create the functionality of the “MustDo” class. </li></ul>
  47. 47. Final (Don’t Change) <ul><li>In some instances of programming, a constant class, method or variable needs to be defined. </li></ul><ul><li>These are variables that do not change once they are set. </li></ul><ul><li>A class and method can be declared that a child class can not over write or perform overriding. </li></ul><ul><li>One example of a variable used in this way: </li></ul><ul><li>final boolean DEBUG = false; </li></ul><ul><li>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. </li></ul><ul><li>During the instance of an object, the static variable can also be added to only allow the creation of the globally: </li></ul><ul><li> static final boolean DEBUG = false; </li></ul>
  48. 48. Import <ul><li>The theme of Java has been abstraction, re-use, and frameworks. </li></ul><ul><li>It becomes a daunting task that there are so many frameworks to chose from and many are free. </li></ul><ul><li>By default, the “import” keyword is used to pull in other objects and packages into the file. For instance, the “import*;” statement at the top of the file will give scope to all classes in that the Java IO framework. </li></ul><ul><li>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;” </li></ul>
  49. 49. JAR <ul><li>There are many frameworks, usually called packages, that come standard with Java. </li></ul><ul><li>These frameworks evolve to the Java standard over time. </li></ul><ul><li>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. </li></ul><ul><li>During this period, a programmer who wanted to use the JCE.JAR had to download it separately. The package now comes with the J2SE. </li></ul><ul><li>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. </li></ul><ul><li>The “classpath” is a property of the program that contains the paths of all classes. </li></ul>
  50. 50. JAR Example
  51. 51. Java Properties <ul><li>The program can determine it’s current environmental propeerties by using “System.getProperty()” and set them by “System.setProperty();”. </li></ul><ul><li>Here’s some sample code: </li></ul><ul><li>public class JavaProperty { </li></ul><ul><li>public static void main(String[] args) { </li></ul><ul><li>System. out.println(&quot;Classpath:&quot; + System.getProperty(&quot;java.class.path&quot;)); </li></ul><ul><li>System. out.println(&quot;Java Version:&quot; + System.getProperty(&quot;java.version&quot;)); </li></ul><ul><li>System. out.println(&quot;Java Home:&quot; + System.getProperty(&quot;java.home&quot;)); </li></ul><ul><li>System. out.println(&quot;Operating System:&quot; + System.getProperty(&quot;;)); </li></ul><ul><li>System. out.println(&quot;User's Home:&quot; + System.getProperty(&quot;user.home&quot;)); </li></ul><ul><li>System. setProperty(&quot;user.home&quot;, &quot;C:ocuments and Settings&quot;); </li></ul><ul><li>System. out.println(&quot;User's Home:&quot; + System.getProperty(&quot;user.home&quot;)); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  52. 52. Java Properties <ul><li>Notice that the “user.home” was changed by the program: </li></ul><ul><li>Java Version:1.6.0_07 </li></ul><ul><li>Java Home:C:Program FilesJavajre1.6.0_07 </li></ul><ul><li>Operating System:Windows XP </li></ul><ul><li>User's Home:C:Documents and Settingsqnwa08 </li></ul><ul><li>User's Home:C:Documents and Settings </li></ul>
  53. 53. Packages <ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>Part of the import statement tells which subdirectory to find the file starting from the JAR or classpath. </li></ul><ul><li>Subsequently, the file had to define this path and subsequent “import” statement by using the “package” keyword: </li></ul><ul><li>package javax.crypto; </li></ul><ul><li>public class Cipher { } </li></ul><ul><li>This is very important when creating packages or your own frameworks and to organize them in a directory structure. </li></ul>
  54. 54. INPUT/OUTPUT (I/O)
  55. 55. Strings <ul><li>A String is an immutable object that contains an array of bytes or characters. </li></ul><ul><li>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. </li></ul><ul><li>A Sample String, “test” is created and then re-created again with a different sequence of characters: </li></ul><ul><li>String test = &quot;You cannot change&quot;; </li></ul><ul><li>test = test.toLowerCase(); </li></ul><ul><li>System.out.println(test); </li></ul>
  56. 56. StringBuffer <ul><li>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. </li></ul><ul><li>A simpler method is to use the “StringBuffer” class. </li></ul><ul><li>The “StringBuffer” class allows its contents to be modified without creating a new class. </li></ul><ul><li>Notice in the following that I did not have to create a new object, the output was “egnahc tonnac uoY”: </li></ul><ul><li>StringBuffer test = new StringBuffer(&quot;You cannot change&quot;); </li></ul><ul><li>test.reverse(); </li></ul><ul><li>System.out.println(test); </li></ul>
  57. 57. Strings <ul><li>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: </li></ul><ul><li>String test =&quot;You&quot; + &quot; cannot &quot; + &quot;change me&quot;; </li></ul><ul><li>int len = &quot;You cannot change me&quot;.length(); </li></ul><ul><li>test = &quot; You &quot;; </li></ul><ul><li>test += &quot;cannot &quot;; </li></ul><ul><li>test += &quot;change me&quot;; </li></ul>
  58. 58. StringTokenizer <ul><li>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. </li></ul><ul><li>Tokens are how humans have the tendency to break characters into individual words, or tokens. </li></ul><ul><li>The “StringTokenizer”, from the “java.util” package is a utility for breaking down the words of a sentence. Here’s a snippet </li></ul><ul><li>String str = &quot;Java,is,Cool&quot;; </li></ul><ul><li>StringTokenizer st = new StringTokenizer(str, &quot;,&quot;); </li></ul><ul><li>while (st.hasMoreTokens()) { </li></ul><ul><li>System.out.print(st.nextToken()+ &quot; &quot;); </li></ul><ul><li>The Output is : Java is Cool </li></ul>
  59. 59. Files <ul><li>When programming Java, it is very important to understand file Input/Output (I/O). </li></ul><ul><li>The File class, , is used for manipulating the file, while classes like Scanner and FileInputStream manage the file’s data. </li></ul><ul><li>The programs in Java have dependencies based on he file structure and works well with manipulation of various files. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul>
  60. 60. Create a File import*; 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. 61. List a Directory with “ls” <ul><li>The File class can also be used for directory calls: </li></ul><ul><li>// List the Directory &quot; ls&quot; </li></ul><ul><li>public class ls { </li></ul><ul><li>public static void main(String argh_my_aching_fingers[]) { </li></ul><ul><li>String[] dir = new;.&quot;).list( ); // Get list of names </li></ul><ul><li>java.util.Arrays. sort(dir); // Sort it (see Recipe 7.8) </li></ul><ul><li>for (int i=0; i<dir.length; i++) </li></ul><ul><li>System. out.println(dir[i]); // Print the list </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Running “ls” will print the directory. </li></ul>
  62. 62. Open a File import; import; 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. 63. Scanner and File <ul><li>The File class is used to create File object that contains information about the open file. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>Regular expressions can also be used with the “java.util.regex.Matcher” class to </li></ul>
  64. 64. Regular Expressions <ul><li>Regular expressions is the process of matching a pattern in a string. </li></ul><ul><li>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;. </li></ul><ul><li>Regular expressions can also be used with the “java.util.regex.Matcher” class, the Pattern class or even the string. </li></ul><ul><li>By comparing the patterns in a string, input can be validated to match proper input. </li></ul><ul><li>The following code snippet shows how to check a zip string so that it matches 5 digits, of course this string passes: </li></ul><ul><li>String zip = “80120”; </li></ul><ul><li>if(zip.matches(&quot;{5}&quot;) == false) </li></ul><ul><li>System.out.println(&quot;Error: zip code&quot;); </li></ul>
  65. 65. Regular Expressions resources
  66. 66. Sockets <ul><li>Sockets are an Application Programming Interface (API) to perform network programming. </li></ul><ul><li>While there is SOA, URL and “java.nio” that abstracts sockets these days, sockets is a basic concept. </li></ul><ul><li>For sockets, there are client sockets that connect to a server through TCP or UDP, and server sockets that are listening for the connection. </li></ul><ul><li>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. </li></ul>
  67. 67. Client Socket <ul><li>A client side socket needs to find the server and connect on s specific port, here is a ftp connection using the “” class: </li></ul><ul><li>try { </li></ul><ul><li>Socket sock = new Socket(“;, 80); </li></ul><ul><li>} catch ( UnknownHostException e ) { </li></ul><ul><li>System.out.println(&quot;Can't find host.&quot;); </li></ul><ul><li> } catch ( IOException e ) { </li></ul><ul><li>System.out.println(&quot;Error connecting to host.&quot;); </li></ul><ul><li>} </li></ul>
  68. 68. Server Socket <ul><li>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. </li></ul><ul><li>Here’s some code that will “listen” on port 80, “accept” the client, and start the thread: </li></ul><ul><li>public class TinyHttpd { </li></ul><ul><li>public static void main( String argv[] ) throws IOException { </li></ul><ul><li>ServerSocket ss = new ServerSocket(80); </li></ul><ul><li>while ( true ) </li></ul><ul><li>new Thread( new TinyHttpdConnection( ss.accept() ) ).start( ); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  69. 69. Httpd (Http Server) continue <ul><li>After we accept the client, we pass the socket to the thread: </li></ul><ul><li>class TinyHttpdConnection implements Runnable { </li></ul><ul><li>Socket client; </li></ul><ul><li>TinyHttpdConnection ( Socket client ) throws SocketException { </li></ul><ul><li>this.client = client; </li></ul><ul><li>} </li></ul><ul><li>public void run( ) { </li></ul><ul><li>try { </li></ul><ul><li>BufferedReader in = new BufferedReader( </li></ul><ul><li>new InputStreamReader(client.getInputStream( ), &quot;8859_1&quot; ) ); </li></ul><ul><li>OutputStream out = client.getOutputStream( ); </li></ul><ul><li>PrintWriter pout = new PrintWriter( </li></ul><ul><li>new OutputStreamWriter(out, &quot;8859_1&quot;), true ); </li></ul><ul><li>String request = in.readLine( ); </li></ul><ul><li>System. out.println( &quot;Request: &quot;+request); </li></ul>
  70. 70. Httpd continue <ul><li>We are going to find a URL in the directory and pass it back to the browser: </li></ul><ul><li>Matcher get = Pattern. compile(&quot;GET /?(*).*&quot;).matcher( request ); </li></ul><ul><li>if ( get.matches( ) ) { </li></ul><ul><li>request =; </li></ul><ul><li>if ( request.endsWith(&quot;/&quot;) || request.equals(&quot;&quot;) ) </li></ul><ul><li>request = request + &quot;index.html&quot;; </li></ul><ul><li>try { </li></ul><ul><li>FileInputStream fis = new FileInputStream ( request ); </li></ul><ul><li>byte [] data = new byte [ 64*1024 ]; </li></ul><ul><li>for(int read; (read = data )) > -1; ) </li></ul><ul><li>out.write( data, 0, read ); </li></ul><ul><li>out.flush( ); </li></ul><ul><li>} catch ( FileNotFoundException e ) { </li></ul><ul><li>pout.println( &quot;404 Object Not Found&quot; ); } </li></ul>
  71. 71. Browsing Httpd <ul><li>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: </li></ul>
  72. 72. URL (Uniform Resource Locators) <ul><li>The “socket” class was a lot of work to simply get a web connection on the client side. </li></ul><ul><li>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. </li></ul><ul><li>Here is an example that will print the index.html from google: </li></ul><ul><li>try { </li></ul><ul><li>URL url = new URL(&quot;;); </li></ul><ul><li>BufferedReader bin = new BufferedReader ( </li></ul><ul><li>new InputStreamReader( url.openStream( ) )); </li></ul><ul><li>String line; </li></ul><ul><li>while ( (line = bin.readLine( )) != null ) </li></ul><ul><li>System. out.println( line ); </li></ul><ul><li>} catch (Exception e) { } </li></ul>
  73. 73. Browsing becomes simplified <ul><li>Many of the URL’s classes become more abstracted by framworks being built on top of frameworks. </li></ul><ul><li>Looking at SWTBrowser example from IBM, the “org.eclipse.swt.browser” abstracts most of the work. </li></ul><ul><li>The Standard Widget Toolkit (SWT) is GUI framework built by IBM for the Eclipse IDE. </li></ul>
  74. 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();; while (!thisClass.sShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } //The URL is called in the createSShell code
  75. 75. Browsing becomes simplified
  76. 76. NIO (New I/O) <ul><li>The “java.nio” package introduces new concepts to Input/Output (I/O). </li></ul><ul><li>In the previous cumbersome example of Httpd, a thread was created for every socket. With NIO, the concept now becomes a channel. </li></ul><ul><li>A channel is simply a pipe from the buffer to the I/O device, usually a socket or file. </li></ul><ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>The channel is the conduit between the buffer and I/O device. </li></ul>
  77. 77. Extensible Markup Language (XML) <ul><li>XML is a specification for creating custom markup languages. </li></ul><ul><li>An example of a language that XML can create is Hypertext Markup Language (HTML) that is the language for programming browser code. </li></ul><ul><li>XML is very flexible because it uses tags to describe data elements: </li></ul><ul><li><book>This is a book... </book> </li></ul><ul><li>The XML file is commonly use to transfer language elements over HTTP in the form of Web Services. </li></ul><ul><li>The XMML file must also contain the proper header information to state that the XML version and encoding scheme: </li></ul><ul><li><?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> </li></ul><ul><li>There are several types of parsers for XML but the basic types are Document Object Model (DOM) and Simple API for XML (SAX). </li></ul>
  78. 78. XML and Serialization <ul><li>By using reflection mentioned earlier, the XMLEncoder class can write an object into XML format: </li></ul><ul><li>import*; </li></ul><ul><li>import java.beans.XMLEncoder; </li></ul><ul><li>public class WriteMe { </li></ul><ul><li>public static void main(String[] args) throws IOException{ </li></ul><ul><li>MyData data = new MyData(); </li></ul><ul><li>data.setName(&quot;testXML&quot;); </li></ul><ul><li>XMLEncoder e = new XMLEncoder( </li></ul><ul><li>new BufferedOutputStream( </li></ul><ul><li>new FileOutputStream(&quot;Test.xml&quot;))); </li></ul><ul><li>e.writeObject(data); </li></ul><ul><li>e.close(); </li></ul><ul><li>} } </li></ul>
  79. 79. XML Bean <ul><li>This Value Object, an object that only contains data, is considered a Bean: </li></ul><ul><li>/** Simple data class used as a Bean. */ </li></ul><ul><li>public class MyData{ </li></ul><ul><li>public String name; </li></ul><ul><li>public void setName(String name){ </li></ul><ul><li> = name; </li></ul><ul><li>} </li></ul><ul><li>public String getName(){ </li></ul><ul><li>return name; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  80. 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. 81. SAX <ul><li>SAX, , is a Simple API for XML. </li></ul><ul><li>It basically opens the XML file with an XML reader, and passes the file to a handler. </li></ul><ul><li>The handler will traverse the XML file, parsing the tags for specific input until it finishes with the file. </li></ul>
  82. 82. SAX import; 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. 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. 84. DOM <ul><li>The Document Object Model (DOM) is the XML parsing technique used by most browsers. </li></ul><ul><li>The DOM parser uses a Document Type Definition file that defines the elements in the XML file that makes up the markup language. </li></ul><ul><li>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. </li></ul><ul><li>The Document class is a tree structure that contains the data. </li></ul><ul><li>Since the DocumentBuilder class will parse the file all at once, it requires higher overhead than serially parsing the file as SAX. </li></ul>
  86. 86. Arrays, Loops and Collections <ul><li>This section could easily be labeled “how do we move data in the Java program” </li></ul><ul><li>Arrays – is a bounded collection of the same data type. </li></ul><ul><li>Loops – A loop continues the statements to execute until a condition is met to tell the block of code to stop continuing. </li></ul><ul><li>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. </li></ul>
  87. 87. Arrays <ul><li>By bounded, an array is a fixed size that has to be defined. </li></ul><ul><li>An Array can be single dimension or multi-dimension, but all the data types must be the same. </li></ul>
  88. 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. 89. Arrays, the code <ul><li>for(int i1 = 0; i1 < intArray.length; i1++){ </li></ul><ul><li>System. out.println(&quot;Output for Row [&quot; +i1 +&quot;]&quot;); </li></ul><ul><li>for(int i2 = 0; i2 < intArray[i1].length; i2++){ </li></ul><ul><li>System. out.printf(&quot;%d &quot;, intArray[i1][i2]); </li></ul><ul><li>} </li></ul><ul><li>System. out.println(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Output: </li></ul><ul><li>Output for Row [0] </li></ul><ul><li>1 2 3 </li></ul><ul><li>Output for Row [1] </li></ul><ul><li>4 5 6 7 </li></ul>
  90. 90. Conditionals <ul><li>Before understanding loops, it is important to understand conditionals , or control statements. </li></ul><ul><li>A conditional changes the path of execution of code based on a condition being met or not. </li></ul><ul><li>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”. </li></ul><ul><li>The basic conditional is the “if” statement, simply put, if this is true then do this statement else do something else: </li></ul><ul><li>if(true) </li></ul><ul><li>System.out.println(&quot;Do the right thing&quot;); </li></ul><ul><li>else </li></ul><ul><li>System.out.println(&quot;Do soemthing else&quot;); </li></ul>
  91. 91. if, else if, else <ul><li>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: </li></ul><ul><li>public static void main(String[] args) { </li></ul><ul><li>boolean bDoThis = true, bAlsoThis = true; </li></ul><ul><li>boolean bNotThat = false; </li></ul><ul><li>if(bNotThat){ </li></ul><ul><li>System.out.println(&quot;Don't do&quot;); </li></ul><ul><li>}else if(bDoThis){ </li></ul><ul><li>System.out.print(&quot;This will work&quot;); </li></ul><ul><li>if(bAlsoThis) </li></ul><ul><li>System.out.print(&quot; and this.&quot;); </li></ul><ul><li>}else{ </li></ul><ul><li>System.out.println(&quot;Not this&quot;);}} </li></ul><ul><li>The output is “This will work and this.” </li></ul>
  92. 92. && and || operators <ul><li>Some if statements require multiple conditions to be met or a single condition out of multiple selections. </li></ul><ul><li>When all conditions have to be met, the && (and) operator is used. It states that this and that must be met. </li></ul><ul><li>When a single condition has to be met out of multiple selections, the || operator is used stating this or that must be met. </li></ul><ul><li>Code snippet: </li></ul><ul><li>String myString = &quot;good&quot;; </li></ul><ul><li>String myString2 = &quot;good&quot;; </li></ul><ul><li>if(myString2.length() > 0 || myString.length() > 0) </li></ul><ul><li>System.out.println(&quot;A String is empty&quot;); </li></ul><ul><li>else if(myString.equals(&quot;good&quot;) && myString2.equals(&quot;good&quot;)) </li></ul><ul><li>System.out.println(&quot;Both are good&quot;); </li></ul>
  93. 93. switch <ul><li>To help keep the code clean, the switch statement can be used. </li></ul><ul><li>The switch statement executes paths based on labels. </li></ul><ul><li>A label for the switch statement is a primitive type variable, such as a byte, character, integer, or short. </li></ul><ul><li>A properly formatted switch statement requires a default label in case non of the other conditions are met. </li></ul>
  94. 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. 95. The “for” loop <ul><li>for(int i1 = 0; i1 < intArray.length; i1++) </li></ul><ul><li>System.out.println(&quot;Output for Row [&quot; +i1 +&quot;]&quot;); </li></ul><ul><li>This “for” has three parts, initialization, the conditional, and the execution. </li></ul><ul><li>Following the “for loop” is the block of execution that will be executed until the condition is false. </li></ul><ul><li>In the statement “for(int i1 = 0” the interger “i1” is initialized to 0 for the execution of the loop. </li></ul><ul><li>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. </li></ul><ul><li>The “i1” is incremented by the “i1++)” statement after the completion of each loop. </li></ul>
  96. 96. The “for each” loop <ul><li>double[] ar = {1.2, 3.0, 0.8}; </li></ul><ul><li>int sum = 0; </li></ul><ul><li>for (double d : ar) { // d gets successively each value in ar. </li></ul><ul><li>sum += d; </li></ul><ul><li>} </li></ul><ul><li>Only access . Elements can not be assigned to, eg, not to increment each element in a collection. </li></ul><ul><li>Only single structure . It's not possible to traverse two structures at once, eg, to compare two arrays. </li></ul><ul><li>Only single element . Use only for single element access, eg, not to compare successive elements. </li></ul><ul><li>Only forward . It's possible to iterate only forward by single steps. </li></ul><ul><li>At least Java 5 . Don't use it if you need compatibility with versions before Java 5. </li></ul>
  97. 97. The “while” loop <ul><li>The “while” loop is a simpler loop that will only execute it’s block of instructions until a condition is no longer met. </li></ul><ul><li>A “while” loop could easily replace a “for” loop with less built-in statements: </li></ul><ul><li>int i1 = 0; </li></ul><ul><li>while(i1 < intArray.length){ </li></ul><ul><li>System.out.println(&quot;Output for Row [&quot; +i1 +&quot;]&quot;); </li></ul><ul><li>i1++; </li></ul><ul><li>Just like a “for” loop can replace the simple pieces of a while loop: </li></ul><ul><li>boolean condition = true; </li></ul><ul><li>while(condition) </li></ul><ul><li>could be rewritten to : for(boolean condition = true; condition; ) </li></ul>
  98. 98. Let’s “break” and “continue <ul><li>The continue keyword can be used for the for , while , and do-while loops. </li></ul><ul><li>Its purpose is to stop the current iteration of the loop and start the next iteration of the loop. </li></ul><ul><li>The continue statement can be labeled or unlabeled. </li></ul><ul><li>The break statement breaks out of the loop completely. </li></ul>
  99. 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. 100. Benefits of Collections <ul><li>A collection is simply a organized group of objects or data types. </li></ul><ul><li>Their benefit’s include: </li></ul><ul><li>Reducing the program effort by providing the plumbing already. </li></ul><ul><li>Increase the program speed and quality by using methods that have been proven in the industry. </li></ul><ul><li>Allows interoperability among unrelated API’s by using the same interfaces. </li></ul><ul><li>Fosters software reuse, reduces effort and the learning curve by using frameworks that have already been created. </li></ul><ul><li>Examples of collections include Vector, Lists, HashTables, Sets and Maps. </li></ul>
  101. 101. Linked List <ul><li>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]”. </li></ul><ul><li>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. </li></ul><ul><li>For this reason linked lists are often used. </li></ul><ul><li>A link list uses a link to index the list to walk down the data: </li></ul>
  102. 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. 103. Labs <ul><li>Build a Hello World. </li></ul><ul><li>Create a Loop with a conditional and array. </li></ul><ul><li>Create a program with a Collection. </li></ul><ul><li>Create a file. </li></ul>