< Java Tutorial

Java type casting

← Previous Next →


Type casting allows us to convert one data type into other. In other words Assigning a value of one type to a variable of another type is known as Type Casting.

In Java, type casting is classified into two types.

Widening Casting(Implicit):

An implicit cast means you don't have to write code for the cast. An implicit cast happens when you're doing a widening conversion.

                               byte->short->int->long->float->double
                               --------------------------------------------------------->
                                              Widening Casting

Example :

public class Test 
{
   public static void main(String[] args)
   {
        int i = 100; 
        long l = i; //no explicit type casting required
        float f = l; //no explicit type casting required

        System.out.println("Int value "+i);
        System.out.println("Long value "+l);
        System.out.println("Float value "+f);
   }
}

 

Output :

Int value 100
Long value 100
Float value 100.0


Narrowing casting( Explicitly done):

An explicit cast means you have to write code for the cast.an explicit cast happens when you're doing a Narrowing conversion.
In other words When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.

                                  double->float->long->int->short->byte
                               --------------------------------------------------------->
                                              Narrowing Casting

Example :

public class Test 
{
    public static void main(String[] args)
    {
        double d = 100.04;
        long l = (long)d; //explicit type casting required
        int i = (int)l; //explicit type casting required

        System.out.println("Double value "+d);
        System.out.println("Long value "+l);
        System.out.println("Int value "+i);
    }
}

Output :

Double value 100.04
Long value 100
Int value 100
← Previous Next →