How do I exit a while loop in Java?
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);
while(obj != null){
// statements.
}
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) {
....
}