Priydarshi Singh Priydarshi Singh - 4 years ago 156
Java Question

Why is Java Compiler giving an incoherent ".class expected" error?

If I have a piece of code like :

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 1 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.

So, I am not surprised that an error is produced.

What surprises me is that the error says '.class' expected.

So what is Java compiler trying to say?

enter image description here

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download