Type Casting

When the value of one primitive data type is assigned to another type, the process is known as Typecasting.

It is possible that when you assign the value of one primitive data type to another data type, the two types might not be compatible with each other. When the data types are compatible, then Java will perform Automatic Type Conversion. In other words, the conversion will be done automatically. However, if data types are not compatible, then they need to be cast or converted explicitly.

Types of casting :

  • Widening Casting  –
    • It converts a smaller type to the larger type size.
    • It happens automatically or implicitly.
    • The two types are compatible.
    • The source type is smaller than the target type.
    • It is also known as Promotion.
    • byte to short, short to int, int to long, long to float, float to double.
Widening Casting
  • Narrowing Casting  –
    • It converts a larger type to a smaller size type.
    • It is performed manually or explicitly.
    • The two types are not compatible.
    • The source type is larger than the target type.
    • It is also known as Demotion.
    • double to float, float to long, long to int, int to short, short to byte.
Narrowing Casting
//Automatic or Widening Casting
int i = 100;
long l = i;
float f = l;

//Manual or Narrowing Casting
double d = 100.04;
long l = (long)d;
int i = (int)l;
Scroll to Top