+ 2
int x = 1; while(x > 0) { System.out.println(x); if(x == 4) { break; } x++; }
I can't understand the break statement
3 odpowiedzi
+ 5
See x=1 and it enters the while loop and satisfies the condition that 1>0 so it prints 1 and checks for if condition but if condition is false because 1 is not equal to 4 so x is now incremented using x++. Now value of x becomes 2 and again it is greater than 0. This goes on and when x becomes 4 the if condition is true and break is executed. So the loop is broken and it comes out of the loop.
Before exiting the loop 1 2 3 4 will be printed.
+ 5
It will happen when x becomes 4.
+ 4
Break is a way to interrupt a loop. So in this case when the variable x equals to 4 it goes out of the while loop.