If I write something like this
System.out.println(18);
Which type has the '18'? Is it int or byte? Or doesn't it have a type yet?
It can't be int, because something like this is correct:
byte b = 3;
And this is incorrect:
int i = 3;
byte bb = i; //error!
EDIT: I think I found the right part in the spec at Assignment Conversion :
The compile-time narrowing of constants means that code such as:
byte theAnswer = 42;
is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:
byte theAnswer = (byte) 42; // cast is permitted but not required
This
is known as an integer literal. There are all sorts of literals, floating point,
String
, character, etc.In the following,
the literal
3
is an integer literal. It's also a constant expression. And since Java can tell that3
fits in abyte
, it can safely apply a narrowing primitive conversion and store the result in abyte
variable.In this
the literal
3
is a constant expression, but the variablei
is not. The compiler simply decides thati
is not a constant expression and therefore doesn't go out of its way to figure out its value, a conversion tobyte
may lose information (how to convert12345
to abyte
?) and should therefore not be allowed. You can override this behavior by makingi
a constant variableor by specifying an explicit cast
The JLS-4.2.1 - Integral Types and Values
And JLS-3.10.1 - Integer Literals
Finally, JLS-3.10.2 - Floating-Point Literals includes
As for
byte b = 3;
it is a Narrowing Conversion fromint
tobyte
.