Java: No byte or short literals?

According to JLS, a literal such as 123 is an int. You can turn it into a long, a float, a double or a char literal by writing 123L, 123f, 123d or '{' respectively, but there’s no way to turn it into a byte or a short literal.

Look mom, no casting!

Still, there’s no casting required here:

byte b = 123;

This is because the language allows for implicit compile-time narrowing of constants.

5.2. Assignment Context

[…]

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable. JLS §5.2

So, technically speaking there’s no byte or short literals. However, a regular int literal (that fits in a byte or a short) can be used as such since it’s implicitly converted to a byte in complie-time.

Similar article

Integers may overflow, but bytes may not? discusses the situation below:

int i = Integer.MAX_VALUE + 1;  // allowed to overflow
byte b = Byte.MAX_VALUE + 1;    // not allowed to overflow

Comments

Be the first to comment!