How do I exit a while loop in Java?

后端 未结 10 2562
情话喂你
情话喂你 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 03:55

    if you write while(true). its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.

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

提交回复
热议问题