Site hosted by Angelfire.com: Build your free website today!
 

Casting

Java allows implicit casting to larger data types, but casting to smaller data types must be done explicitly.

Java allows implicit casting to larger data types, but casting to smaller data types must be done explicitly.

byte b   = 50;
short s   = b;       //Valid because short is 16 bits
                     //easily storing an 8-bit byte.
float f    = 10.0F;
double d  = f;       //A 64-bit double has no problem
                     //storing a 32-bit float.

The following would fail because explicit casting is required:

int i   = 100;
Short s = i;            //Fails!
Short s =(short) i;  //The explicit cast is needed.

If the value stored in i is too big to fit into a short, an error (exception) will occur. We will discuss exceptions later in to course. For the casting rules, please refer to page 2-8 of the course hand-out.