Posted by
Zhullyblog
on
- Get link
- X
- Other Apps
Logically, break means stop. This meaning also applied to programming.
Just as continue statement, a break statement is used in a loop to terminate or stop the loop from running when the condition we have stated have been met.
SYNTAX
Explanation
I said earlier that a break statement is used to terminate a loop. So imagine if you want to print numbers from 1-30 but you want the numbers to stop when the number is 22. Then, what do you do?
The simple logic is use a break statement. The break statement terminates the loop ONCE the numbers are equal to 22.
Let's take an example
Break for While loop
public class sample{
public static void main(String args[]){
int x =0;
while(x<=10)
{
System.out.println("Result : "+x );
if (x==5)
{
break;
}
x++;
}
System.out.println("Loop will stop at 5 because we used a break when num is 5 ");
}
}
Results
Break for "For loop "
public class sample{
public static void main(String args[]){
int num;
for (num =1; num<=15; num ++)
{
System.out.println("Result: "+num);
if (num==8)
{
break;
}
}
}
}
Result
Introduction to Java programming
How to declare a variable in Java
If, if..else statement in Java
Java Object Oriented Programming
Constructors in Java programming
Please share
Please share
Comments
Post a Comment