First of firsts I'm not sure, and this is not sever as "it should compile but it doesn't nor the opposite; so at most it will irritate the coder".
byte b1 = (byte) 1;
Integer b2 = () 1;
So the first is fine and meaningless casting, and is for illustration,
for the second, there are two errors from compiler:
Discussion:
Eclipse compiler suggests a type of byte and not another type, maybe byte is the most similar type to int. and this is OK. The second is obviously wrong, '1' is not byte while compiler is complaining about it like it is the case.
So for Eclipse compiler the second statement is just like:
Integer b2 = (byte) 1;
Eclipse Version: Oxygen.2 Release (4.7.2)
Eclipse Compiler for Java(TM) v20140604-1726, 3.10.0
The Java® Language Specification specifies what is valid Java code and what is not valid Java code. It does not specify the wording of the compiler errors.
Syntax errors are detected quite early during compilation after the character stream has been broken down into so-called tokens (e. g. (
, {
, byte
, variable name, ...). Based on these tokens and the grammar rules, the compiler tries to build an abstract syntax tree.
In your example, this is not possible with the given rules. The problem is that () 1
is not a CastExpression
. There are three rules for CastExpression
:
CastExpression:
( PrimitiveType ) UnaryExpression
( ReferenceType {AdditionalBound} ) UnaryExpressionNotPlusMinus
( ReferenceType {AdditionalBound} ) LambdaExpression
1
can be an UnaryExpression
or an UnaryExpressionNotPlusMinus
, but either a PrimitiveType
or a ReferenceType
is missing between the parentheses. If we always apply the first rule, we get from PrimitiveType
via IntegralType
to the token byte
. The syntax error message includes the first expected next token only instead of listing all possible next tokens.
Integer b2 = (byte) 1;
is syntactically but not semantically correct. In Eclipse, Quick Fix (Ctrl+1) can tell you how to change the code so that it becomes also semantically correct. In your example, the first Quick Fix proposal is Change cast to 'Integer'
.
In short, the compiler says what is wrong and Quick Fix (Ctrl+1) helps to fix it.