O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Casting Between Primitives and Wrappers

Here are the rules about it:

A value of a primitive type can be cast to another primitive type by identity conversion, if the types are the same, or by a widening primitive conversion or a narrowing primitive conversion.

A primitive type value can be cast to a reference type by boxing conversion.

int i = 5; //5 is a primitive int
Integer iRef = i; // convert to wrapper
//reference type: ok

A reference type value can be cast to a primitive type by unboxing conversion.

Integer iRef = new Integer(5); //starts life as
reference type
int j = i; //ok, unboxed to primitive

See the topic on Autoboxing for more about moving seamlessly between primitive and wrapper class types.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required