break
, continue
and return
break
:
- it is used to terminate a statement sequence in a switch statement.
- used to exit out of a loop.
- as a replacement for
goto
class BreakAsGoTo{
public static void main(String[] args){
boolean t = true;
first:{
second:{
third:{
System.out.println("Before the break");
if(t) break second; // break out of the second block
System.out.println("third: This will not execute");
}
System.out.println("second: This will not execute");
}
System.out.println("first: This will execute");
}
}
}
continue
:
- if you want to continue the running the loop but want to skip the processing of remaining code in current iteration then
continue
can be used. - like
goto
,continue
can also be used with label to describe which enclosing loop to continue.
class Continue{
public static void main(String[] args){
outer: for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(j>i){
System.out.println();
continue outer;
}
System.out.print(" *");
}
}
System.out.println();
}
}
return
:
- immediately terminates the method in which it is executed.
- used to explicitly return from a method.
- transfers the program control back to the caller of the method.