Previous
Index

Next

Objective 2, looping, break and continue

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.You can get an idea of the value of the for statement in that many other languages have a very similar construct. For example C/C++ and perl have a for construct. Many programmers use the for construct for most looping requirements as it is compact, self contained, easy to understand and hard to mess up. 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.

It is syntactically correct to create an empty for block that will loop forever thus

for(;;){
        System.out.println("forever");
    }   

It is more compact however to use a while(true) construct thus

while(true){
        System.out.println("true");
    }



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. The expression "spaggetti code" refers to code where it is hard to tell where the logic starts and ends. The goto statement is sometimes known as an "unconditional jump", ie it is possible to write code that jumps from one part of a program to another without even performing a test. 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.

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. According to Elliotte Rusty Harold, a distinguished Java author, “There are only seven uses of continue in the entire Java 1.0.1 source code for the java packages.” This means you are unlikely to get much practice with it in your real world programming and thus you should place emphasis in learning it well for the exam. The creators of the exam questions seem to love creating convoluted netsted loops with breaks and continue statements that you would probably never encounter in good quality real code.

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.

Questions

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

Question 5)

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

public class Anova{
    public static void main(String argv[]){
    Anova an = new Anova();
    an.go();
    }
    public void go(){
    int z=0;
    for(int i=0;i<10; i++,z++){
        System.out.println(z);
    }
    for(;;){
        System.out.println("go");
    }

    }
}

1) Compile time error, the first for statement is malformed
2) Compile time error, the second for statement is malformed
3) Output of 0 to 9 followed by a single output of "go"
4) Output of 0 to 9 followed by constant output of "go"

Question 6

What will be output by the following code?

public class MyFor{
    public static void main(String argv[]){
        int i;
        int j;
    outer:
        for (i=1;i <3;i++)
        inner:
    for(j=1; j<3; j++) {
        if (j==2)
        continue outer;
        System.out.println("Value for i=" + i + " Value for j=" +j);
    }
    }
}



1) Value for i=1 value for j=1
2) Value for i=2 value for j=1
3) Value for i=2 value for j=2
4) Value for i=3 value for j=1

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)

1) 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

Answer 5)

4) Output of 0 to 9 followed by constant output of "go"

The structure of the first for loop is unusual but perfectly legal.

Answer 6 )

1) Value for i=1 value for j=1

2) Value for i=2 value for j=1


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

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

Central Connecticut State University
http://chortle.ccsu.ctstateu.edu/cs151/Notes/chap41/ch41_1.html

Elliotte Rusty Harold
http://www.ibiblio.org/javafaq/course/week2/14.html






Previous
Index

Next