Ayush Agarwal
Ayush Agarwal Blogs


Ayush Agarwal Blogs

Typecasting In Java

Typecasting In Java

Ayush Agarwal's photo
Ayush Agarwal
·Jan 8, 2021·

2 min read

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

Did you find this article valuable?

Support Ayush Agarwal by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this