Type Casting in java

Converting one data type into another data type is calling Type Casting .

Type Casting in Java is nothing but converting a primitive or interface or class in Java into other type. There is a rule in Java Language that classes or interface which shares the same type hierrachy only can be typecasted. If there is no relationship between then Java will throw ClassCastException .

Type casting are of two types they are
1 ) Implicit Casting (Widening)
2 ) Explicit Casting (Narrowing)


Implicit / Widening / Automatic type converion

Automatic conversion of smaller data type into higher data type by JVM is called Implicit type casting.
Automatic type conversion can happen if both type are compatible and target type is larger than source type.

//example of implicite Type Casting
class Example
{
	public static void main(String args[])
	{
	    byte i = 50;
	    // No casting needed for below conversion
	    short j = i;
	    int k = j;
	    long l = k;
	    float m = l;
	    double n = m;
	    
	    System.out.println("byte value : "+i);
	    System.out.println("short value : "+j);
	    System.out.println("int value : "+k);
	    System.out.println("long value : "+l);
	    System.out.println("float value : "+m);
	    System.out.println("double value : "+n);
	}
}
byte value : 50
short value : 50
int value : 50
long value : 50
float value : 50.0
double value : 50.0

Explicit / Narrowing Type Casting

Converting higher data type into lower datatype forcefully by programmer is called Explicit Type Casting .
When you are assigning a larger type to a smaller type, then Explicit Casting is required.


//example of Explicit Type Casting
 class Example 
{
	public static void main(String args[])
	{
		double d = 75.0;
		// Explicit casting is needed for below conversion
		float f = (float) d;
		long l = (long) f;
		int i  = (int) l;
		short s = (short) i;
		byte b = (byte) s;
		
		System.out.println("double value : "+d);
		System.out.println("float value : "+f);
		System.out.println("long value : "+l);
		System.out.println("int value : "+i);
		System.out.println("short value : "+s);
		System.out.println("byte value : "+b);
	}
}
double value : 75.0
float value : 75.0
long value : 75
int value : 75
short value : 75
byte value : 75
woman avatar