How do I exit a while loop in Java?

后端 未结 10 2529
情话喂你
情话喂你 2020-11-27 03:50

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

For example, my code is currently as follows:

while(true){
    if(obj == null){

                


        
10条回答
  •  死守一世寂寞
    2020-11-27 04:00

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

提交回复
热议问题