Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the assignment of a short variable to an Integer reference produce a compile time error?

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?

like image 319
kauray Avatar asked Nov 23 '15 09:11

kauray


People also ask

Can we assign short to int in Java?

The java. lang. Short. intValue() method returns the value of this Short as an int.

Which method is used to assign the integer values at runtime?

Integer intValue() Method in Java Return Type: A numeric value that is represented by the object after conversion to the integer type.

What is the effect of converting an integer to byte justify?

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.

Can int be assigned to long?

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.


2 Answers

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
like image 92
Thilo Avatar answered Oct 02 '22 12:10

Thilo


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.

like image 21
SomeJavaGuy Avatar answered Oct 02 '22 14:10

SomeJavaGuy