int x = 1; while(x > 0) { System.out.println(x); if(x == 4) { break; } x++; } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

int x = 1; while(x > 0) { System.out.println(x); if(x == 4) { break; } x++; }

I can't understand the break statement

5th Nov 2019, 3:23 AM
Minhaj Haider
Minhaj Haider - avatar
3 Answers
+ 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.
5th Nov 2019, 3:30 AM
Avinesh
Avinesh - avatar
+ 5
It will happen when x becomes 4.
5th Nov 2019, 5:18 AM
Sonic
Sonic - avatar
+ 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.
5th Nov 2019, 3:26 AM
Rodrigo Oliveira
Rodrigo Oliveira - avatar