0 0
Read Time:1 Minute, 11 Second

Java Type Casting (Conversion)

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

//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;
	   //Widening Casting
        double b=a;
        double d=25.5385;
        //Narrowing Casting
		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
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %