Classes/Objects  «Prev 


Converting and Casting in Java

Mastery of converting and casting is very important to do well on the certification exam. Several test questions assume that you know when and how numeric promotion takes place, when primitive types and objects are converted to String objects, and when casting is allowed or required.
This example illustrates that what is type casting? Type Casting refers to changing an entity of one datatype into another. This is important for the type conversion in developing any application. If you will store a int value into a byte variable directly, this will be illegal operation.
For storing your calculated int value in a byte variable you will have to change the type of resultant data which has to be stored.This type of operation has illustrated below :
In this example we will see that how to convert the data type by using type casting. In the given line of the code

c = (char)(t?1:0); 

illustrates that if t which is boolean type variable is true then value of c which is the char type variable will be 1 but 1 is a numeric value. So, 1 is changed into character according to the Unicode value. But in this line
 c = (char)(t?'1':'0'); 
 

1 is already given as a character which will be stored as it is in the char type variable c.