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.
if
.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?
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 whichint
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.
See more on this question at Stackoverflow