简体   繁体   中英

Does variable initialization is not valid in while loop?

When doing homework,I found an error when I'm using do while loop and while loop. It successfully run the variable initialization in do while loop.But not in the while loop.Why is that?What is the reason?

class Example{
    public static void main(String args[]){
        int x=100;
        int a,b;

        do{
            a=10;
        }while(x>0);

        while(x>0){
            b=10;
        }
        System.out.println(a);
        System.out.println(b);
    }
}

Error:

variable b might not have been initialized
System.out.println(b);
                   ^1 error

That's the main difference between the while loop and the do-while loop: the do-while executes at least once no matter what condition it has; the while loop may never execute depending on its condition. So in your case variable a will be initialized in the do-while body, but if the condition in the while loop is false, its body won't be executed and hence variable b won't be initialized. The compiler won't analize your code to determine if the condition in your while loop is true or not. It will just not compile and throw the error you see in your console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM