How do I exit a while loop in Java? How do I exit a while loop in Java? java java

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);