+ 3

Why we use 'break' in java?

Why we use 'break' in java?

9th Oct 2017, 12:48 AM
조이현
4 odpowiedzi
+ 14
//to come out of a loop //example ::: int x = 1; while(x > 0) { System.out.println(x); if(x == 4) { break; } x++; } /* Outputs 1 2 3 4 */ //hope it helps☺
9th Oct 2017, 2:47 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 11
Loop is immediately terminated and the program control resumes at the next statement following the loop. If you don't use break then the loop will not be terminated and the program will not give you the output.
9th Oct 2017, 5:11 AM
Mayank Sakhare
Mayank Sakhare - avatar
+ 4
I understood. 'break' is to stop any loops.
9th Oct 2017, 12:54 AM
조이현
+ 4
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. And It can be used to terminate a case in the switch statement.  for example-- public class Test { public static void main(String args[]) { int [] numbers = {1, 2, 3, 4, 5}; for(int x : numbers ) { if( x == 3 ) { break; } System.out.print( x ); System.out.print("\n"); } } } it's output will be--- 1 2
9th Oct 2017, 2:14 AM
Giriraj Raikwar
Giriraj Raikwar - avatar