How to exit a while loop in Java?

What is the best way to exit / end a while loop in Java?

For example, my code currently looks like this:

while(true){ if(obj == null){ // I need to exit here } } 
+52
java while-loop break exit
Oct 31 '11 at 9:15
source share
8 answers

Use break :

 while (true) { .... if (obj == null) { break; } .... } 



However, if your code looks exactly as you indicated, you can use the usual while and change the condition to obj != null :

 while (obj != null) { .... } 
+127
Oct 31 '11 at 9:16
source share
 while(obj != null){ // statements. } 
+6
Oct 31 '11 at 9:17
source share

break is what you are looking for:

 while (true) { if (obj == null) break; } 

restructure your loop:

 while (obj != null) { // do stuff } 

or

 do { // do stuff } while (obj != null); 
+3
Oct 31 '11 at 9:18
source share

Finding a while...do construct with while(true) in my code will make my eyes bleed. Instead, use the standard while :

 while (obj != null){ ... } 

And look at the Yacoby link provided in it, and this one too. Jokes aside.

While and do-while operations

+3
Oct 31 '11 at 9:19
source share

Take a look at Oracle's Java โ„ข Tutorials .

But basically, as dacwe said , use break .

If you can often avoid using break and put the check as a condition of the while loop or use something like a while loop. This is not always possible.

+2
Oct 31 '11 at 9:16
source share

You can perform several logical state tests as part of the while () check using the same rules as in any logical check.

 while ( obj != null && True ) { // do stuff } 

works like

 while ( value > 5 && value < 10 ) { // do stuff } 

. Conditional are checked at each iteration loop. As soon as one does not match, the while () loop will be completed. You can also use break;

 while ( value > 5 ) { if ( value > 10 ) { break; } ... } 
+1
Dec 10
source share

You can use the "break" already mentioned in the answers above. If you need to return some values. You can use "return" as shown below:

  while(true){ if(some condition){ do something; return;} else{ do something; return;} } 

in this case, it is still under the method returning some values.

0
Oct 13 '14 at 19:58
source share

if you write while (true) . this means that the loop will not stop in any situation, to stop this loop, you need to use the break statement between the blocks.

 package com.java.demo; /** * @author Ankit Sood Apr 20, 2017 */ public class Demo { /** * The main method. * * @param args * the arguments */ public static void main(String[] args) { /* Initialize while loop */ while (true) { /* * You have to declare some condition to stop while loop * In which situation or condition you want to terminate while loop. * conditions like: if(condition){break}, if(var==10){break} etc... */ /* break keyword is for stop while loop */ break; } } } 
0
Apr 20 '17 at 10:18
source share



All Articles