Credits

Saturday, February 21, 2009

Java's Break from Loop Structures

We have to sometimes use a force exit from a loop or go to certain structures. Java uses break and goto to perform these actions.

Check the sample program below to evaluate break command.



[+/-] show/hide




//break samples as label
class breakdemo1{
public static void main(String args[])
{
done:
for(int i=0;i<10;i++){
for (int j=0;j<10;j++){
for (int k=0;k<10;k++){
System.out.println (k+ " ");
if (k==5) break done; //jump to done;
}
System.out.println("After k loop"); //wont execute
}
System.out.println("After j loop"); //wont execute
}
System.out.println("After i loop");
}
}

//break as goto
class breakdemo1{
public static void main(String args[])
{
int i;
for (i=1 ;i<4>

one: {
two: {
three: { System.out.println("\n i is " +i);
if (i==1) break one;
if (i==2) break two;
if (i==3) break three;
//this is never reached
System.out.println("wont print.");
}
System.out.println("After block three.");
}
System.out.println("After block two.");
}
System.out.println("After block one.");
}
System.out.println ("After for statement");
}
}


// break inside loop
class breakdemo{
public static void main(String args[])
throws java.io.IOException{
char ch;
for ( ; ;)
{
ch=(char)System.in.read(); //get a char
if (ch=='\n') break;
}
System.out.println("You pressed Enter key");

}
}

//break inside loop
class breakdemo{
public static void main(String args[]){
int num=100;
//loop while i-squared is less than num
for (int i=0; i
if (i*i>=num) break; //terminate the loop
System.out.print(i+" ");
}
System.out.println("Loop complete.");
}

}

AddThis