break keyword

break keyword in Java

Syntax

// condition
break;

Program

 
public class break_demo
{
public static void main(String args[])
{
for(int i=1; i<=10; i++)
{
if(i==6)
{
break;
}
System.out.println(i);
}
}
}

Output

 
1
2
3
4
5

Explanation

The Java break is used to break loop or switch statement. It breaks the current flow of the program at specified condition.

break keyword in inner loop

Program

 
public class break_inner
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=5; j++)
{
if(i==3 && j==3)
{
break;
}
System.out.println(i + "-" + j);
}
}
}
}

Output

 
1-1
1-2
1-3
1-4
1-5
2-1
2-2
2-3
2-4
2-5
3-1
3-2
4-1
4-2
4-3
4-4
4-5
5-1
5-2
5-3
5-4
5-5

Explanation

It breaks inner loop only if you use break statement inside the inner loop.Outer loop will continue to iterate.

Comments

Popular posts from this blog

System.Environment

System.Console

Datatype and keyword