Java program on typecasting and conversion

Type casting and conversion

Typecasting and Conversion

Today we will learn about the Java Type Casting and its types with the help of examples.
Casting is a process of changing one type of value to another type. In Java, we can cast one type of value to another type. It is known as typecasting.

In Java, typecasting is classified into two types,

  1. Widening Casting(Implicit) or Automatic type conversion

Automatic Typecasting takes place when,

  • the two types are compatible
  • the target type is larger than the source type

typecasting type-1

public class Test
{
    public static void main(String[] args)
    {
      int i = 60;
      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);
    }
}

Program Output:

Int value 60
Long value 60
Float value 60.0

2. Narrowing Casting(Explicitly done)

When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit typecasting. If we don’t perform casting then compiler reports compile-time error.

typecasting type-2

public class Test
{
    public static void main(String[] args)
    {
      double d = 60.03;
      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);
    }

}

Program Output:

Double value 60.03
Long value 60
Int value 60

I hope this post helps you to understand Typecasting & Conversion and its implementation in Java programming language.

Keep coding 🙂

2 thoughts on “Java program on typecasting and conversion”

Leave a Reply

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