I have the following code in Java :
class Boxing
{
public static void main(String args[])
{
short s = 10;
Integer iRef = s;
}
}
Why does it produce an error in compilation? If I explicitly typecast the short to an integer in the expression, it compiles successfully. Since I'm using a short in an expression isn't the type of that supposed to be an integer by default without requiring the explicit case?
The java. lang. Short. intValue() method returns the value of this Short as an int.
Integer intValue() Method in Java Return Type: A numeric value that is represented by the object after conversion to the integer type.
When an integer value is converted into a byte, Java cuts-off the left-most 24 bits. We will be using bitwise AND to mask all of the extraneous sign bits.
Java int can be converted to long in two simple ways:Using a simple assignment. This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.
You want to have two things happening here: widening and auto-boxing.
Unfortunately, Java does only one of the two automatically. The reason for that is most likely that autoboxing was introduced fairly late (in Java5), and they had to be careful to not break existing code.
You can do
int is = s; // widening
Short sRef = s; // autoboxing
Integer iRef = (int) s; // explicit widening, then autoboxing
Here´s the documentation from JLS 5.1.7
Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:
From type boolean to type Boolean
From type byte to type Byte
From type short to type Short
From type char to type Character
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double
From the null type to the null type
Basicly the direct conversion from short
to Integer
is not part of the autoboxing process of Java
.
The autoboxing, as provided above, is only able to implicity cast the representing primitive type to it´s representing Wrapper class. Since this is not the case it will cause a compile time error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With