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 or a double literal by writing 123L, 123f or 123d 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.

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

Comments

Be the first to comment!