0

Newbie question.

Why does the first code segment print out "0" while the second returns errors?

Error free code.

public class test 
{
    public int c;
    public test()
    {
        System.out.println(c); //prints out 0
    }
    public static void main(String args[])
    {
        test t = new test();
        t.printC();
    }
}

Code that doesn't compile

int i;
System.out.println(i); //returns a error in main method as well as other methods.

Compiling 2nd code segment with javac terminal command (OS X)-

test.java:12: error: variable i might not have been initialized
        System.out.println(i);
                           ^

Compiling 2nd code segment with Eclipse-

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The local variable i may not have been initialized

    at test.test.main(test.java:14)
champfish
  • 73
  • 7
  • 1
    A local variable is required to be initialized. An instance variable is, however, initialized implicitely to its default value (0 for an int). Eclipse uses its own compiler, which replace the code not compiled by an Error; that's why you're able to run the code. – Alexis C. Feb 17 '15 at 22:36
  • @ZouZou Thanks for the quick response. Is there a particular reason why this is so? – champfish Feb 17 '15 at 22:38
  • Because that's how the behaviour was defined in the JLS §16. – Andy Turner Feb 17 '15 at 22:41
  • @champfish The answer is: because the JLS defines it and so the compiler must follow this rules. If you want a rationale, you can read this thread - http://stackoverflow.com/questions/1560685/why-must-local-variables-including-primitives-always-be-initialized-in-java – Alexis C. Feb 17 '15 at 22:42

1 Answers1

0

As @ZouZou linked to, local variables must always be initialized but instance variables do not. This is because the compiler has no way to know what order methods are being called and thus doesn't know whether instance variables have been initialized yet.

champfish
  • 73
  • 7