Learning Java
Custom Search

Previous Next

Casting

When data conversion is not automatic, casting can be used. Casting is the process of changing a value from one type to another using the following format. The (typename) changes the value to the new type.

    (typename)variable

Boolean values of true or false cannot be cast.

Some casting examples:

    (int)a
    (float)x + 1.2f
    3.25d * (double)(5 * i + 7)

In the following, we have 3 variables, int i, byte b, and long l. When we try to compile the code, it complains that we can lose precision when we try to place the value of i into the smaller area of b. However, it has no problem with placing the value of i into the larger area of l.

public class CastTest {

   public static void main(String args[]) {

	int i = 63;
	byte b = i;
	long l = i;

	System.out.println("i=" + i + "  b=" + b + "  l=" + l);
   }
}

However, if we should cast the int i before moving it into b, the compiler no longer has a problem. It's leaving the responsibility of assuring that i is not too large for b to contain.

public class CastTest {

   public static void main(String args[]) {

	int i = 63;
	byte b = (byte)i;
	long l = i;

	System.out.println("i=" + i + "  b=" + b + "  l=" + l);
   }
}

Let's set int i to a value greater than the maximum value of a byte (127). In the execution, we get an overflow in b and what is left is not the 150 we placed there, but -106.

    int i = 150;

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved