Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promotion of primitive types

I have a question about the promotion of primitive types in Java. As we can see in the following example, one of the methods does not compile due to an error of type mismatch. Each method returns the same value but in different types.

The version of primitive long method works without error while the version of wrapper class Long fails. This is because the int literal in the return statement will be first promoted to a broader primitive type (e.g. long) and then to the corresponding wrapper class Integer and so on. Since Integer is not a subclass of Long the compiler gives an error.

But why does the version of wrapper class Byte works without any error? What exactly does the compiler do at this point?

long getPrimitiveLong() {
    return 12; // valid
}

Long getWrapperLong() {
    return 12; // Error: type mismatch
}

Byte getWrapperByte() {
    return 12; // valid
}
like image 838
Nurettin Armutcu Avatar asked Dec 19 '22 03:12

Nurettin Armutcu


1 Answers

The version with Byte works through some compiler magic.

Unlike long numeric literals which can be constructed with a L suffix, e.g. 12L, there is no such thing as a byte literal. That is why Java compiler treats numeric literals that fit in a byte as byte literals. Hence, 12 in your last example is considered a constant of type byte.

Java Language Specification offers a description of this conversion in section 5.2:

A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:

  • Byte and the value of the constant expression is representable in the type byte.
  • Short and the value of the constant expression is representable in the type short.
  • Character and the value of the constant expression is representable in the type char.
like image 53
Sergey Kalinichenko Avatar answered Jan 05 '23 20:01

Sergey Kalinichenko