Extension and boxing with java

In the Java programming language, extension and boxing do not work, but how does it work in the following example?

final short myshort = 10;
Integer iRef5 = myshort; 

Why does this work? Is this not the same as an extension and then a window?

But if I write the following code:

final int myint = 10;
Long myLONG = myint;

why doesn't it work?

+5
source share
7 answers

With java 7, both examples do not work. You will get below exceptions:

Type mismatch: cannot convert from short to Integer
Type mismatch: cannot convert from int to Long

Because the problem is not due to boxing, but because of the transformation.

+1
source

Following what others have said, I can confirm that I can compile your first example with the Eclipse compiler, but not the second. C compiler javac, both are not compiled as Vlad said

, ! JLS, , : -)

+2

( javac 1.6.0_26 Sun/Oracle, Linux). . .

b.java:4: incompatible types
found   : short
required: java.lang.Integer
        Integer iRef5 = myshort; 
                        ^
b.java:7: incompatible types
found   : int
required: java.lang.Long
        Long myLONG = myint;
                      ^
2 errors
+1

, , .

final int myint = 10;
Long myLONG = (long) myint;
+1

, :

final short myshort = 10;
Integer iRef5 = myshort; 

, ( , : ).

, :

final short myshort = 10;
final Short box = new Short(myshort);  // boxing: so that objects are assignable.
Integer iRef5 = box;  // widening: this fails as Integer is not a superclass of Short

( ), . , , , JLS. . / JLS .

+1

, Java

int

, long

float, float

double, double

, int. . "


0

box wide, widen, box

So

final short myshort = 10;
Integer iRef5 = myshort; 

final short myshort = 10;
Integer iRef5 = 10; 

Long myLONG = 10;//this won't compile , 

10L, , , object i.e. Object o = 10L;


.

0

All Articles