Tuesday, February 12, 2013

SCJP: widening and narrowing

Widening means promoting a smaller type into a bigger one. No cast is needed. Look at the picture taken from book A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition), Khalid Mughal, that shows the chain of widening types. char is at the side, because it is signed, while the others are unsigned.

This is also applicable to the type hierarchy:

Object obj = "123" ; // no cast is needed: widening String to Object (subtype to supertype), also called upcasting

Narrowing means converting a wider type into a smaller one, meaning that there is loss of magnitude and precision. So a cast is needed.

String str = (String) obj // a cast is needed: narrowing an Object to a String (supertype to subtype), also called downcasting

The compiler will reject casts that are not legal, with a ClassCastException (runtime exception), but pay attention that narrowing a primitive type will never result in a runtime exception.

No comments:

Post a Comment