1

In Java if we provide following statement, it will produce compilation error:

class A {

public static void main(String[] args){
    int i = 10;
    int j;
    if(i == 10) {
       j = 20;
    }
    System.out.println(j);
   }
}

But in the following statement, no compilation error:

class A{ 

public static void main(String[] args){
    int i = 10;
    int j;
    if(i == 10) {
       j = 20;
     }
    else {
       j = 30;
     }
    System.out.println(j);
    }
  }

Neither this produces compilation error:

class A{
    public static void main(String[] args) {
       final int i = 10;
       int j;
       if(i == 10){
          j = 20;
         }
       System.out.println(j);
      }
     }

What is the reason?

Pr4njal
  • 83
  • 1
  • 1
  • 7
  • 1
    In your second code snippet, because of your `if-else` `j` is guaranteed to be initialized eventually in one way or the other. – QBrute Oct 27 '16 at 10:09
  • The last code doesn't compile since `j` is not declated. Not sure what you expected. But a local variable [must be initialized](http://stackoverflow.com/questions/415687/why-are-local-variables-not-initialized-in-java) before being used. Which is what the linked question explains, with the same code as you have. Look also at the "Related" questions containing the exact same error. – Tunaki Oct 27 '16 at 10:44
  • @Tunaki yeah there were some minor mistakes, now you can check it and the link you provided was different from this question – Pr4njal Oct 27 '16 at 10:51
  • That is exactly the same code as your first example. Please, refer to the linked question and all of its related questions. A local variable **must be** initialized. – Tunaki Oct 27 '16 at 10:52
  • @Tunaki My last example may be little bit same but I have declared `int i`as `final`. Due to this change, last one gets compiled but not the first one, even though in both `j` isn't initialized. – Pr4njal Oct 27 '16 at 11:03
  • 1
    Why are you focusing on what the compiler will do? [The Java Language Specification mandates the code **not** to compile](http://stackoverflow.com/questions/415687/why-are-local-variables-not-initialized-in-java). It would be an error for the compiler to compile that code. It doesn't even matter that the `if` is always true: the spec says that code must not compile, regardless of what the checked conditions actually are. – Tunaki Oct 27 '16 at 12:20

1 Answers1

1

In the first snippet, the compiler doesn't analyze the value of i to determine that if(i == 10) would always be true and hence j would also be initialized.

Therefore, as far as the compiler is concerned, if the condition is evaluated to false, j is never initialized and cannot be accessed.

The second snippet is guaranteed to always initialize j, either in the if clause or the else clause. Therefore it passes compilation.

Eran
  • 387,369
  • 54
  • 702
  • 768