-4

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
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50

1 Answers1

3

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.

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
  • So if i want to print b,what should I do is to make the while loop true?If you can kindly add the code,it will be easy for me to understand. – K.Anuradha Dec 26 '17 at 15:25
  • No. The compiler won't analize your code to determine if the condition is true or not. It will just not compile doing this with a while loop. – Juan Carlos Mendoza Dec 26 '17 at 15:29