Casting and Conversion in Java

First of all, let’s understand what typecasting is. In Java, Typecasting is a process that converts one data type into another data type. It is done in both ways manually and automatically. The automatic conversion is done by the compiler and the manual conversion is performed by the programmer. The compiler does the automatic conversion and for manual conversion, it has to be done by the individuals.

Now let’s discuss type casting and its types with code.

Types of typecasting in Java

1. Widening Typecasting:

In widening typecasting or implicit conversion, there’s a conversion of lower data type into the higher data type and the compiler converts the data type automatically.

The flow of data types are as follows:

byte -> short -> char -> int ->long -> float ->double.

Let’s understand this with the help of a code:

class Casting
{
   public static void main(String...args)
   {
       int i = 1;
       long l = i;
       double d = i;    //converts automatical       
       System.out.println(i);
      System.out.println(d);
      System.out.println(l);
    }
}

Output:

1

1.0

1

In the above code, the compiler will automatically convert int data type into double.

 

2. Narrowing Typecasting:

In narrowing typecasting or explicit conversion, there’s a conversion of a higher datatype into a lower datatype and we have to do it manually.

The flow of datatypes are as follows:

double -> float -> long -> int -> char -> short -> byte

Let’s understand this with the help of code:

class Casting{
         public static void main(String...args)
              {
                 double d = 1.54;
                 long l = (long)d;
                 int i = (int)d;  //Here we have done typecasting manually
                
                System.out.println(d);
                System.out.println(i);
                System.out.println(l);
               }
              }

Output:

1.54

1

1

In the above code, we have manually done typecasting by placing the data type in round brackets in front of the value.

Java also provides Java literals to cast:

f = for float type casting

D = for double type casting

L  = for long type casting

Leave a Reply

Your email address will not be published. Required fields are marked *