Search code examples
javacompiler-errors

Why does the Java compiler only report one kind of error at a time?


I've a snippet

class T{
    int y;
    public static void main(String... s){
        int x;
        System.out.println(x);
        System.out.println(y);
    }
}

Here there are two error, but on compilation why only one error is shown?

The error shown is:

non-static variable y cannot be referenced from a static context
    System.out.println(y);
                       ^

But what about the error

variable x might not have been initialized
    System.out.println(x);
                       ^

Solution

  • The Java compiler compiles your code in several passes. In each pass, certain kinds of errors are detected. In your example, javac doesn't look to see whether x may be initialised or not, until the rest of the code actually passes the previous compiler pass.