Type Casting

When value of one data type is assigned to another data type variable, known as type casting. A large data size data variable can hold small data size type's value. For example a float variable can be assigned byte, short, int and long without any loss of precision.

Precedence of Data types

char --> int 		
byte--> short --> int --> long --> float --> double

Important ! boolean data variable or value can't be type casted into another data type variable.

Order of data type decides what type of value a variable can store. For example char value can be assigned to integer variable.

Example :

class literal
   public static void main(String arg[])
	 long l=123L;
	 // Although data size of float is 4 byte and long data size is 8 byte
     // In precedence of data type float is superior than long
     // That's why float can have long value	 
	 float f=l;

In above program long value automatically converted into float data type. This conversion is known as implicit type casting.

Explicit Type casting

Explicit type casting involve assigning a value of large data size to small data size variable. This rule doesn't apply for long (8 byte) and float (4 byte). For example if we assign a float value to integer variable then compiler won't allow compilation of the program. In order to assign a float value to integer variable, casting has to be specified explicitly.

Syntax for type casting

Variable = ( Type of Variable) [ data value or expression ]

Data value or result of a expression can be type casted into data type of variable. When we assign large data size value to small data size variable, loss of information will happen.


	  // file: type.java
	  // www.jgyan.com 
class type
  public static void main(String arg[])
     double d=1.23;
	 int i=(int)d;