Why is the Java compiler giving the incoherent ".class expected" compile error?

If I have a piece of code like this:

public class ABC {
    public static void main(String[] args) {
        if (true)
            int a = 0;
    }
}

When I compile it, Java compiler produces an error

.class expected.

  • I know that when we don't use braces, we can use only one statement after if.
  • And I also know that I will not be able to use the int variable a, because as soon as the ; is encountered, the program comes out of if, and the variable a loses it's scope.

I am not surprised that this code emits an error, but why is the error message '.class' expected?

What is Java compiler trying to say?

Screenshot of compiler error

Jon Skeet
people
quotationmark

I suspect the problem is that the only token sequence that can legitimately follow the keyword token of int in this case is . followed by class. The declaration statement you've got at the moment isn't valid because a local variable declaration on its own isn't a Statement as per JLS 14. (It's a BlockStatement.)

Note that in the tutorialspoint environment referenced in the comment, if you use a class instead of int, a different error is produced - potentially because the set of valid tokens is different in that scenario. (String.getClass(); would be valid for example, whereas int.getClass(); wouldn't.)

There is a valid question asked in a comment:

Why this .class thing? If you know any situation in which int followed by .class can compile, then please tell me.

And that's easy - you can call a method on the Class reference returned by int.class:

public class ABC
{
    public static void main(String args[])
    {
        if(true)
            int.class.getName();
    }
}

That's not useful code, but it is valid code. It compiles for me without warnings or errors.

As mentioned in comments, more recent compiler versions give more useful errors - I would recommend upgrading.

people

See more on this question at Stackoverflow