Break statement in Java

Break statement in Java

Break statement in Java is used to break loop or switch statement. It breaks the flow of the program and the control resumes at the next statement. break statement can be used in all types of loops.

Q. Write a program to show the use of break statement in java.

Code-

class example
{
  public static void main(String[] args) {
    int i=1;
    while(true)
    {
	if(i>5)
	    break;
	System.out.println(i);
	i++;
    }
  }
}

Output-

break statement output java

Explanation-

Firstly integer ‘i’ is declared with value 1. Then while loop is declared. Now if the condition bracket of while loop is given as true the loop executes endlessly. So the loop will continue to print the value of ‘i’ and increment. Then if condition is checked. So when the value of ‘i’ reaches 6, break statement will be executed. Thus the control comes out of the loop and the program terminates.

Program parts-

  1. class– Used to declare a class in java.
  2. public– Access modifier which represents it is visible to all.
  3. static– The main method is declared as static, so it doesn’t require to create an object to invoke the main method.
  4. void– Return type of the method.
  5. main– Represents the starting point of the program.
  6. String[] args– Used for command line argument.
  7. System.out.println()– System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. System.out.println is used to print a statement.

Conclusion-

So this is the concept of break statement in Java. We hope it was clear to you. If you have any doubts tell us in the comment section. For daily updates and more such content do follow us on Instagram.

Keep programming!

ErrorFreeProgram.

Leave a Reply

Your email address will not be published. Required fields are marked *