Type Casting in Java


Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion.

There are two types of casting in Java as follows:

  1. Widening Casting (automatically)
  2. Narrowing Casting (manually)

1. Widening Casting (automatically)

  • This type of casting takes place when two data types are automatically converted. It is also known as Implicit Conversion. This involves the conversion of a smaller data type to the larger type size.
  • byte -> short -> char -> int -> long -> float -> double

2. Narrowing Casting (manually)

  • if you want to assign a value of larger data type to a smaller data type, you can perform Explicit type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be done.
  • double -> float -> long -> int -> char -> short -> byte

Source Code

//04 Type Casting in Java
/*
	Widening Casting
		byte -> short -> char -> int -> long -> float -> double
	Narrowing Casting
		double -> float -> long -> int -> char -> short -> byte
*/
import java.lang.*;
 
class casting
{
	public static void main(String args[])
	{
		int a=10;
		double b=a,d=25.5385;
		int c=(int)d;
		System.out.println("Int : "+a);
		System.out.println("Double : "+b);
		System.out.println("Double : "+d);
		System.out.println("Int : "+c);
 
 
 
 
	}
}

Output

Int    : 10
Double : 10.0
Double : 25.5385
Int    : 25
To download raw file Click Here

Basic Programs