Using break to Exit a Loop :
When a break statement is encountered inside a loop, the loop is
terminated and program control resumes at the next statement following the loop. The break
statement can be used with any of Java’s loops (while, do..while, for loops)
Example :
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
if(i == 5)
break;
System.out.print(i + “ “);
}
System.out.println("Loop complete.");
}
}
output:
0 1 2 3 4 Loop complete.
Using break in nested loops : When used inside a set of nested loops, the break statement will
only break out of the innermost loop.
Example:
class BreakOnlyInnerLoop
{
public static void main(String args[])
{
for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
if(j == 2)
break;
System.out.print(j+ “ “);
}
System.out.print(i+ “ “);
}
System.out.println("Loops complete.");
}
}
Output: 0 1 0 0 1 1 0 1 2 Loops complete.
Using break to Exit a outer Loop in nested loops concept as a Form of Goto : Here, label is
the name of a label that identifies a block of code. When this form of break executes, control is
transferred out of the named block of code. One of the most common uses for a labeled break
statement is to exit from nested loops. (Asst. Prof. Viral S. Patel)
Example:
class BreakOuterLoop
{
public static void main(String args[])
{
outer : for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
if(j == 2)
break outer;
System.out.print(j+ “ “);
}
System.out.print(i+ “ “);
}
System.out.println("Loops complete.");
}
}
Output: 0 1 Loops complete.
Using continue in single loop:
The Java continue statement is used to continue current flow of the program and skips the
remaining code at specified condition.
Example :
class Continue
{
public static void main(String args[])
{
for(int i=0; i<5; i++)
{
if(i == 2)
continue;
System.out.print(i + “ “);
}
System.out.println("Loop complete.");
}
}
output: 0 1 3 4 Loop complete.
Using continue in nested Loop to continue outer loop : continue may specify a label to
describe which enclosing loop to continue.
Example :
class Continue
{
public static void main(String args[])
{
outer : for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
if(j == 2)
continue outer;
System.out.print(j+ “ “);
}
System.out.print(“This statement does not exit.“);
}
System.out.println("Loops complete.");
}
}
Output: 0 1 0 1 0 1 Loops complete.
Return :
The return statement is used to explicitly return from a method. That is, it causes program control
to transfer back to the caller of the method.
Example :
class Return
{
public static void main(String args[])
{
for(int i=0; i<3; i++)
{
for(int j=0; j<5; j++)
{
if(j == 2)
return;
System.out.print(j+ “ “);
}
System.out.print(“This statement does not exit.“);
}
System.out.println("This statement also does not exit.“);
}
}
Output: 0 1
Comments
Post a Comment