How do I exit a while loop in Java?
Use break
:
while (true) {
....
if (obj == null) {
break;
}
....
}
However, if your code looks exactly like you have specified you can use a normal while
loop and change the condition to obj != null
:
while (obj != null) {
....
}
while(obj != null){
// statements.
}
break
is what you're looking for:
while (true) {
if (obj == null) break;
}
alternatively, restructure your loop:
while (obj != null) {
// do stuff
}
or:
do {
// do stuff
} while (obj != null);
Finding a while...do
construct with while(true)
in my code would make my eyes bleed. Use a standard while
loop instead:
while (obj != null){
...
}
And take a look at the link Yacoby provided in his answer, and this one too. Seriously.
The while and do-while Statements