Reputation: 1
Is type casting possible between wrapper classes in Java?
The code here is what I tried:
public class Test
{
public static void main(String[] args)
{
Double d = 100.04;
Long l = (long) d.doubleValue(); //explicit type casting required
int i = (int) l; //explicit type casting required
System.out.println("Double value " + d);
System.out.println("Long value " + l);
System.out.println("Int value " + i);
}
}
Why isn't Long
casted to int
in this program?
Upvotes: 0
Views: 6674
Reputation: 5649
Long l = (long)d.doubleValue(); //explicit type casting required
int i = (int)l; //Not valid, because here you are casting a Wrapper Long
In above line, casting of l is not possible to int because Wrapper classes are only by Autoboxing and Unboxing. Refer: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html. Wrapper class is casted only to its corresponding primitive type.
long l = (long)d.doubleValue(); //explicit type casting required
int i = (int)l; //valid, because here you are casting primitive to primitive
In above lines casting of l is possible to int because long is primitive type and int is also a primitive type. Here primitive narrowing casting will take place as casting from long to int may result in loss of some precision.
Upvotes: 2
Reputation: 72844
The Java Language Specification does not allow casting from a reference type to a primitive if it is not by unboxing conversion:
The compile-time legality of a casting conversion is as follows:
An expression of a primitive type may undergo casting conversion to another primitive type, by an identity conversion (if the types are the same), or by a widening primitive conversion, or by a narrowing primitive conversion, or by a widening and narrowing primitive conversion.
An expression of a primitive type may undergo casting conversion to a reference type without error, by boxing conversion.
An expression of a reference type may undergo casting conversion to a primitive type without error, by unboxing conversion.
An expression of a reference type may undergo casting conversion to another reference type if no compile-time error occurs given the rules in §5.5.1.
So the only primitive type to which a Long
can be cast is long
. If you declare the variable of type long
(the primitive type), the cast will compile:
long l = (long) d.doubleValue();
int i = (int) l;
Upvotes: 1