Return to Tutorial Index

Back to the home page of this site

morterboard

Java2 Certification
Tutorial

 

You can discuss this topic with others at http://www.jchq.net/discus
Read reviews and buy a Java Certification book at http://www.jchq.net/bookreviews/jcertbooks.htm


2) Flow Control and Exception Handling

Objective 2)

Write code using all forms of loops including labeled and unlabeled use of break and continue and state the values taken by loop counter variables during and after loop execution.

The for statement

The most common method of looping is to use the for statement. Like C++ and unlike C, the variable that controls the looping can be created and initialised from within the for statement. Thus 

public class MyLoop{
      public static void main(String argv[]){
      MyLoop ml = new MyLoop();
      ml.amethod();
      }
       public void amethod(){
                for(int K=0;K<5l;K++){ 
                     System.out.println("Outer "+K); 
                     for(int L=0;L<5;L++)
                     {System.out.println("Inner "+L);}
                   }
          }
}

This code will loop 5 times around the inner loop for every time around the outer loop. Thus the output will read

Outer 0; 
Inner 0 
Inner 1 
Inner 2 
Inner 3 
inner 4 
Outer 1; 
Inner 0 
Inner 2

etc etc 

The for statement is the equivalent of a for/next loop in Visual Basic. You may consider the syntax to be

for(initialization; conditional expression;increment)

The conditional expression must be a boolean test in a similar way to an if statement. In the code example above the for statement was followed by a code block marked by curly braces. In the same way that an if statement does not demand a block you can have a for statement that simply drives the following line thus

        for(int i=0;i<5;i++)
                System.out.println(i);

Note that in neither versions do you terminate the for line with a semi colon. If you do, the for loop will just spin around until the condition is met and then the program will continue in a "straight line". You do not have to create the initialisation variable (in this case) within the for loop, but if you do it means the variable will go out of scope as soon as you exit the loop. This can be considered an advantage in terms of keeping the scope of variables as small as possible.

The while loops and do loops, nothing unexpected

The while and do loops perform much as you would expect from the equivalent in other languages.

Thus a while will perform zero or more times according to a test and the do will perform one or more times. For a while loop the syntax is

while(condition){
        bodyOfLoop;
}

The condition is a boolean test just like with an if statement. Again you cannot use the C/C++ convention of 0 for true or any other value for false

So you might create a while loop as follows

while(i<4){
        i++;
        System.out.println("Loop value is :"i);
}

Note that if the variable i was 4 or more when you reached the while statement would not result in any output. By contrast a do loop will always execute once.

Thus with the following code you will always get at least one set of output whatever the value of the variable i on entering the loop.

do{
        System.out.println("value of : "+i);
        } while (i <4);

Many programmers try to use the for loop instead of do while loop as it can concentrate the creation initialisation, test and incrementation of a counter all on one line.

The goto statement, science or religion?

The designers of Java decided that they agreed with programming guru Edsger Dijkstra who wrote a famous article titled "Goto considered harmful". Because indiscriminate use of goto statements can result in hard to maintain spaghetti code it has fallen out of use and considered bad programming style. There are situations when it would be useful and to help in those situations Java offers the labeled and unlabeled versions of the break and continue keywords.

Break and continue

These statements allow you to conditionally break out of loops. They do not however, allow you to simply jump to another part of the program. The exam is likely to include questions covering this subject in the form of a set of nested loops. You have to work out what numbers will be printed out before the loops finish due to the action of the break statement.

Here is an example of the sort of irritating question you are likely to get in the exam

public class Br{
public static void main(String argv[]){
        Br b = new Br();
        b.amethod();
        }
        public void amethod(){
        for(int i=0;i <3;i ++){
        System.out.println("i"+i+"\n");
        outer://<==Point of this example
                if(i>2){
                break outer;//<==Point of this example
                }//End of if
               for(int j=0; j <4 && i<3; j++){
                       System.out.println("j"+j);
                       }//End of for
         }//End of for
     }//end of Br method                
}

You then have to pick out which combination of letters are output by the code. By the way the code "\n" means to output a blank line.

Jump to a label

It is often desirable to jump from an inner loop to an outer loop according to some condition. You can do this with the use of the labeled break and continue statement.

A label is simply a non key word with a colon placed after it. By placing the name of the label after break or continue your code will jump to the label. This is handy for making part of a loop conditional. You could of course do this with an if statement but a break statement can be convenient. You cannot jump to another loop or method but exiting the current loop is often very useful.

The break statement abandons processing of the current loop entirely, the continue statement only abandons the currently processing time around the loop.

Take the following example

public class LabLoop{
                public static void main(String argv[]){
                LabLoop ml = new LabLoop();
  ml.amethod();
   }
        public void amethod(){
                outer:
                for(int i=0;i<2;i++){ 
                                for(int j=0;j<3;j++) {
                                if(j>1)
			                //Try this with break instead of continue
		        	        continue outer;
	                		System.out.println("i "+ i + " j "+j);
				    }
                        }//End of outer for
                        System.out.println("Continuing");
		 }
}


This version gives the following output

i 0 j 0
i 0 j 1
i 1 j 0
i 1 j 1


Continuing

If you were to substitute the continue command with break, the i counter would stop at zero as the processing of the outer loop would be abandoned instead of simply continuing to the next increment.


 

Question 1)

What will happen when you attempt to compile and run the following code in a method?

        for(int i=0;i<5;){
                System.out.println(i);
                i++;
                continue;
                }
   

1) Compile time error, malformed for statement
2) Compile time error continue within for loop
3) runtime error continue statement not reached
4) compile and run with output 0 to 4



Question 2)


What will happen when you attempt to compile and run the following code?

public class LabLoop{
                public static void main(String argv[]){
                LabLoop ml = new LabLoop();
  ml.amethod();
                mainmethod:
                System.out.println("Continuing");
                }
        public void amethod(){
                outer:
                for(int i=0;i<2;i++){ 
                       for(int j=0;j<3;j++){
                           if(j>1)
                              break mainmethod;
                              System.out.println("i "+ i + " j "+j);
                    }
        }//End of outer for
  }
}


1)
i 0 j 0
i 0 j 1
Continuing

2)

i 0 j 0
i 0 j 1
i 1 j 0
i 1 j 1
Continuing
3) 

Compile time error

4)
i 0 j 0
i 0 j 1
i 1 j 0
i 1 j 1
i 2 j 1
Continuing


Question 3)

What will happen when you attempt to compile and run the following code?

public void amethod(){
                outer:
                for(int i=0;i<2;i++){
                        for(int j=0;j<2;j++){
                             System.out.println("i="+i + " j= "+j);
                                        if(i >0)
                                             break outer;
                                }

             }
              System.out.println("Continuing with i set to ="+i);
       }

1) Compile time error

2)

i=0 j= 0
i=0 j= 1
i=1 j= 0
3)
i=0 j= 0
i=0 j= 1
i=1 j= 0
i=2 j= 0
4)

i=0 j= 0
i=0 j= 1


Question 4)

What will happen when you attempt to compile and run the following code?

        int i=0;
        while(i>0){
                System.out.println("Value of i: "+i);
        }
                do{
                        System.out.println(i);
                        } while (i <2);
                }
1) 
Value of i: 0 
followed by 
0
1
2

2)

0
1
2

3)

Value of i: 0 
Followed by continuous output of 0








4) Continuous output of 0

Answers

Answer 1)


4) compile and run with output 0 to 4

This is a strange but perfectly legal version of the for statement


Answer 2)


3) Compile time error

You cannot arbitrarily jump to another method, this would bring back all the evils manifest in the goto statement


Answer 3)

1) Compile time error

This is not really a question about break and continue. This code will not compile because the variable is no longer visible outside the for loop. Thus the final System.out.println statement will cause a compile time error.


Answer 4)


4) Continuous output of 0

There is no increment of any value and a while loop will not execute at all if its test is not true the on the first time around


Other sources on this subject
The Sun Tutorial

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html

Jyothi Krishnan
http://www.geocities.com/SiliconValley/Network/3693/obj_sec2.html#obj6

Richard Baldwin
http://www.Geocities.com/Athens/Acropolis/3797/Java026.htm#flow of control

Bruce Eckel Thinking in Java
http://codeguru.earthweb.com/java/tij/tij0045.shtml#Heading131

Last updated
28 Dec 1999
copyright © Marcus Green 1999
most recent version at www.jchq.net