Search code examples
javascjp

Why int value must be initlize in first case mentioned below?


I have two different cases where I have used boolean in if condition. Why I need to initialize variable p in CASE 1?

CASE 1:

public static void main(String[] args) {
    int p;
    if(Boolean.TRUE){
        p=100;
    }
    System.out.println(p);
}

CASE 2:

public static void main(String[] args) {
    int p;
    if(Boolean.TRUE){
        p=100;
    }
    System.out.println(p);
}

Solution

  • Simple answer from Oracle:

    Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

    And although p is always initialized from the if statement, but the compiler will investigate all the cases of a wrapper Boolean. To solve it:

    public static void main(String[] args) {
       int p;
       if(Boolean.TRUE){
           p=100;
       } else {
           p= 0; //for example. The compiler will see all the cases are covered
       }
       System.out.println(p);
    }//no error