0

Why this doesn't want compile, if in other condition like if(8>0) will

public class StartClass {
public static void main(String[] args) {
    int i;
    boolean b = true;
    if (b) {
        i = 1;
    }
    System.out.println(i);//error
}
}
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
oleh
  • 9
  • 4
  • 2
    Because `i` is not necessarily initialized. The compiler doesn't realize that `b` will always be true. – Eli Sadoff Nov 21 '16 at 20:27
  • 1
    It works with `(8>0)` because that is replaced with true. It will also work if you declare `b` as `final`. – Compass Nov 21 '16 at 20:31
  • See also [What is the design rational for “variable may not have been initialized”?](http://stackoverflow.com/questions/20283742/what-is-the-design-rational-for-variable-may-not-have-been-initialized) – Andy Thomas Nov 21 '16 at 20:42
  • thnks) final will solve – oleh Nov 22 '16 at 21:15

1 Answers1

0

The answer is:

java doesn't give initial value to variable declared inside methods..

int i is declared inside the main method, so there is no default initial value for that...

if b never gets to be true then i never gets initialized,

So the compiler complains because it may happen that i has no value ergo: you are not going to be able to do System.out.println(i);

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97