IfElse

     

If/Else

The if/else statement is used to execute code when a test condition is true.

 

 if (x > 10) {    System.out.println("x is greater than 10"); } else {    System.out.println("x is less than 10"); } 

Switch/Case and Breaks

The following code shows how to use a switch/case construct with a char . But any of the following primitive types are legal to test against: char , byte , short , or int .

 

 switch (test) { case 'A' :       System.out.print("Found X");       break; //Print 'X' if test = 'X'    case 'B' :       System.out.print("Found Y");       break; //Print 'Y' if test = 'Y'    default :       //This code runs if test does not equal 'X' or 'Y'       System.out.print("Found Z"); } 

If neither break were there, and if test equaled 'X', the code would print XYZ. Java switch/case constructs "fall through" until they encounter a break statement or the end of the switch.

The break keyword is used to stop processing within a case statement. Note that the keyword default is used to specify the statement to execute in the event that the passed number does not equal any of the explicit case values.

While Loop

The while loop performs its test against the truth value of the expression before the loop executes. That means that if the test expression is initially false, the loop will never run.

 

 int x = 0; while (x < 10) {    System.out.println(" x is now : " + x);    //increment x by 1    x++; } System.out.println("x is not less than 10 anymore: " + x); 

Note that we are only able to refer to the variable x outside the loop because it was declared outside the loop. If you declare a variable inside a loop, you won't be able to reference it outside the loop.

Do-While Loop

The do-while loop differs from the while loop in two ways. Most importantly, the code is guaranteed to run at least once, even if the test expression evaluates to false on the first test. That is the point of this loop. The second way it is different is that it is hardly ever used. I mean, hardly ever used at all. But it's easy.

 

 int x = 0; do {    System.out.println(" x < 10 : " + x);    x++; } while (x < 10); // test not performed until after  // code block is executed at least once System.out.println("x is not less than 10 anymore: " + x); 

For Loop

The for loop is perhaps the most popular of all loops . It comes in two versions: one for iterating against a test expression, not unlike the while loop, and a second for iterating once for each item in a collection (such as an array or Hashtable ).

The first kind of for loop has the following basic structure:

 

 for(initialize a variable; test the expression; operation to perform after iteration of loop) { //statements to execute when loop is true } 

Here is a simple example:

 

 for (int x = 0; x < 10; x++){    System.out.println(" x < 10 : " + x); } 

Note that at this point in the code, we cannot refer to the current value of x (10) out here. That's because we didn't declare it outside of the for loop, but rather declared the variable as part of the loop construct itself.

You may optionally omit the curly braces used around the statement that executes in the event that the test condition returns true . However, you must keep in mind that only the first statement following the for loop will be executed; if you want to do more than one thing inside the for loop, you have to use the curly braces. Otherwise, that second line of code doesn't get executed until the loop exits entirely (the test condition returns false ).

Complex For Loop

The for loop can also facilitate more complex statements. Taking the same basic structure illustrated in the preceding sections, you can add initializing statements and more operations to be performed after the loop iterates. The additional initializers and operations are separated by commas. Here is what I'm talking about:

 

 //two initializers and two post-loop operations for(x=0, y=0; x <10; x++, y++); 

Here is an example:

 

 private static void complexFor(){    int iStop = 8;    int jStop = 21;    for (int i = 0, j = 0; ((i < iStop) &&        (j <= jStop)) ;                                     i++, j=i * 3)       {// \t is the tab character       System.out.println("i: " + i + "\tj: " + j);    } } 

Note that in Java a simple semicolon ( ; ) usually used to mark the end of a statement is also considered a complete statement itself. That makes the following entirely legal:

 

 int i = 0, j = 5; for ( ; i < j; i++, j++ ) { ; ; } 

From the cool-and-weird-code-to-impress-your- friends department: ask them to write the simplest possible legal for loop that executes a statement. Here's the answer:

 

 for ( ; ; ) ; 

Then for a practical joke, have them run the code. Can you guess what happens? It's an infinite loop that runs until it crashes their virtual machine! Hilarious. No one ever tires of a really good joke .

graphics/fridge_icon.jpg

FRIDGE

Note for Nerds

The for loop actually compiles into a while loop in Javaland. Because they do the same thing, the compiler finds it more efficient to just manage one of them. So in a sense, a for loop is syntactic sugar. Which is weird for such a mainstay kind of a statement. But this is not true of the foreach loop, which behaves differently.


Nested For Loop

You can nest these different constructs within each other. You can put a while loop inside a for loop, and so forth. You'll find that putting one for loop inside another is commonly necessary. To demonstrate , let's print a multiplication table through 10, making a new line after every 10 results.

 

 private static void timesTable(){    for (int i = 1; i <= 10; i++){       for (int j = 1; j <= 10; j++){          System.out.print(i * j + "\t");       }       System.out.println();//makes a new line    } } 

Here, we use the \t character to separate each result with a tab.

Continue and Labels

The continue keyword is used to skip the current iteration of a loop if some test condition returns true. There are two ways to use it. The first is without a label.

 

 //the continue statement must be used inside a loop, //or your code won't compile. private static void demoContinue(){    for (int i=1; i <= 100; i++){       if ((i % 4) != 0)          continue;       System.out.println(i);    } } 

The preceding code will print out every multiple of 4 between 4 and 100, inclusive. It does so by testing: "If I divide the current number by 4 and do not get a remainder of zero, don't print out this number." The continue keyword causes program execution to jump into the next iteration of the loop.

The second way to use continue is with a label, which allows you to explicitly state the place in your code you want to jump to. These are sort of useful for inner loops. In fact, a label must be specified immediately prior to a loop definition. You can just put a label anywhere and jump to it with continue . Here's an example:

 

 private static void demoContinueLabel(){       //here outer: is a label indicating       //a named reference point in the code       outer:    for (int i=0; i < 4; i++){       for (int j = 0; j < 4; j++){          if (i < 2)             //go to the label             continue outer;          System.out.println(" i is " + i + " and                 j is " + j);       }    } } 

graphics/fridge_icon.jpg

FRIDGE

There is no goto keyword in Java. It was determined a long time ago that goto is evil and does bad things to good programs. So, although it has no meaning in the Java language, you are not free to use it as an identifier (variable name ), because goto is a reserved word.


This code produces the following result:

 

 i is 2 and j is 0 i is 2 and j is 1 i is 2 and j is 2 i is 2 and j is 3 i is 3 and j is 0 i is 3 and j is 1 i is 3 and j is 2 i is 3 and j is 3 

That's because the continue keyword is used to jump out to execute the next statement after the label we named outer in the event that i is less than 2. So, the print statement is only reached when i is equal to or greater than 2.

Labels are almost never used in Java. Neither is the continue keyword for that matter.

They're considered kind of bad practice. Although it works great in the preceding example, if you catch yourself starting to type continue inside a loop, stop, put your hands up, and step away from the keyboard. Consider if it is really necessary. You'll find it is perhaps never necessary, and you can simplify your code in more obvious ways that improve its readability and predictability.

graphics/fridge_icon.jpg

FRIDGE

We won't talk about Collections until the sequel to this book, More Java Garage , but for now know that they are Sets, Hashtables, Vectors, ArrayLists, and other things that you might be familiar with. If none of that is ringing a bell, Java Collections (in a gross generalization) often act like resizable arrays. They're different classes that store lists of objects that you can iterate over.


Enhanced For Loop (for each loop)

The enhanced for loop, which acts like the for each loop that you might be familiar with from other languages such as VB.NET and C#, gives you way to cleanly iterate over a collection with less fuss and muss.

Here is the syntax of the for each loop:

for (ElementType element : expression) statement

That syntax translates to this in practice:

 

 for (Object o : myCollection)        { //do something with o } 

Note that the expression must be an instance of a new interface, called java.lang.Iterable , or an array. The java.util.Collection interface has been retrofitted to extend Iterable . The exclusive job of this new interface is to offer the opportunity for implementing classes to be the target of the new for each loop.

graphics/fridge_icon.jpg

FRIDGE

This example uses a complete class to demonstrate the for-each loop. Don't worry if this looks unfamiliar to you. There are more examples without the surrounding class code. We'll get to classes in a moment.


The authors of the Java language preferred the colon to adding a couple of keywords ( foreach , and in ), because adding keywords can leave a language vulnerable to a lot of retro-fitting difficulties. I sort of hated the colon syntax at first, but now I like it because it is very easy to spot in code. This kind of loop is often represented like this in other languages:

foreach (ElementType element in collection) statement //C#

The preceding syntax uses the foreach keyword, which I find very readable and intuitive. And it's not like the Java authors haven't added keywords to the language before ( assert was added in 1.4). Maybe there is a ton of code out there using foreach and in as identifiers (!). Well, either way, I'm happy it's here.

Let's see it in action.

ForLoop.java
 

 package net.javagarage.efor; import java.util.*; /* demos how to use the enhanced for loop that is new with Java 5.0. it acts like a foreach loop in other languages such as VB.NET and C#. */ public class ForLoop { public static void main(String[] ar){       ForLoop test = new ForLoop();       for (Kitty k : test.makeCollection())       System.out.println(k);       }       public ArrayList<Kitty> makeCollection(){          ArrayList<Kitty> kitties = new ArrayList<Kitty>();          kitties.add(new Kitty("Doodle"));          kitties.add(new Kitty("Noodle"));          kitties.add(new Kitty("Apache Tomcat"));          return kitties;       } } class Kitty {    private String name;    public Kitty(String name) {       this.name = name;    }    public String toString(){       return "This kitty is: " + name;    } } 

The output is as expected:

 

 This kitty is: Doodle This kitty is: Noodle This kitty is: Apache Tomcat 

You can also use the enhanced for loop with arrays:

 

 package net.javagarage.efor; public class ArrayForLoop {    public static void main(String[] ar){    /*this says, 'for each string in the array    returned by the call to the makeArray() method,    execute the code' in this case println)*/    for (String s : makeArray())       System.out.println("Item " + s);    public static String[] makeArray(){       String[] a = new String[] {"a","b","c"};       return a;    } } 

This looping construct affects only the compiler, not the runtime, so you shouldn't notice any difference in speed. A for loop is compiled into a while loop anyway, so there is a lot of sharing going on under that particular hood.

The array form of the for : statement generates a compiler error in the event that the array element cannot be converted to the desired type via assignment conversion. Here is an example of using the foreach loop to loop over an array:

 

 int sum(int[] a) {       int result = 0;       for (int i : a)          result += i;       return result; } 

This code says, "declare an int called 'result' with a value of 0 to start with." Then, for every int in the passed in array (called 'a'), call the current iteration value 'i' and add it to the result. Very simple, clean, elegant.

Notice that the new loop does not use the term for each like other programming languages (such as C#) do. Instead, it uses a : . The new syntax is cleaner and simpler. When you combine the simplicity of the for each loop with the new power of generics (introduced in Java 5.0, and discussed in the upcoming book More Java Garage ), you can write very clear and clean code.

 

 void processNewOrders(Collection<Order> c) { for (Order order : c) order.process(): } 

This code is immediately understandable: you see what type you are using in the signature and in the for loop. It is shorter, and every line lets you know what kind of type you are dealing with. As you might guess, it works with nested loops too.

Okay. Nuff said.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net