Ayush Agarwal's Blog

Ayush Agarwal's Blog

Typecasting In Java

Typecasting In Java

Subscribe to my newsletter and never miss my upcoming articles

Hello everyone! It's a new year and the first Friday of this year, so time for another blog.

Today on the table, we have an exciting and relatively unheard topic in Java - "Typecasting."

What is Typecasting?

Typecasting is When we assign a value of one primitive data type to another type—for example, converting from int to double or byte to short.

There are two types of typecasting:-

  1. Widening or Automatic Type Conversion- As the name suggests, automatic type conversion happens when two types are compatible. In this case, the most important is that the destination type's size is larger than the source type.

  2. Narrowing or Explicit Type Conversion- When we need to assign a larger type value to a variable of a smaller type, we need to perform explicit typecasting.

Let us understand the above two concepts with a sample code:

public static void main(String[] args)
{
      int i=100;
      long l1=i;         // automatic typecasting where long is converted to int

      double d=100.3;
      long l2=(long)d;    //explicit typecasting
      System.out.println(i);
      System.out.println(l1);
      System.out.println(d);
      System.out.println(l2);
}
Output:
100
100
100.04
100
 
Share this