Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why during autoboxing final long to Byte compilation error happens, but final int to Byte is ok?

There is no error during auto-boxing of constants with int and short types to Byte, but constant with long type do has error. Why?

final int i = 3;
Byte b = i; // no error

final short s = 3;
Byte b = s; // no error


final long l = 3;
Byte b = l; // error
like image 270
Назар Кулян Avatar asked Sep 13 '17 20:09

Назар Кулян


People also ask

How does Autoboxing of integer work in Java?

Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is: Passed as a parameter to a method that expects an object of the corresponding wrapper class.

What happens in Autoboxing?

Autoboxing in Java is a process of converting a primitive data type into an object of its corresponding wrapper class. For example, converting int to Integer class, long to Long class or double to Double class, etc.

What is the major advantage of Autoboxing?

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.

Is Autoboxing and Boxing same?

The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. This is the new feature of Java5. So java programmer doesn't need to write the conversion code.


1 Answers

From JLS Sec 5.2, "Assignment contexts" (emphasis mine):

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • 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.

  • 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.
    • ...

It's simply not allowed for longs by the spec.

Note that the second bullet point here says that this happens irrespective of the boxing: assigning a constant long expression to a byte variable would similarly fail:

// Both compiler errors.
byte primitive = 0L;
Byte wrapped = 0L;
like image 159
Andy Turner Avatar answered Oct 14 '22 04:10

Andy Turner