Java

How To Type Casting In Java?

Casting is the process of converting a value from one primitive data type to another. The figure that follows illustrates the two forms of type casting in Java.

  • Narrowing(explicit) type casting
  • Widening(implicit) type casting

Narrowing Type Casting

Another name for it is explicit type casting. The process is referred to as “narrowing” when a bigger size data type is assigned to a smaller size data type.

Before double variable d and float variable f, you’ll notice an int enclosed in parenthesis. When transferring a value from a bigger size data type to a lower size data type, this is done.

public class JavaExample {
  public static void main(String[] args) {
    double d = 4.55d;
    float f = 1.25f;
    int i = (int)d; // Explicit casting: double to int
    int i2 = (int)f; // Explicit casting: float to int

    System.out.println("Double Value: "+d); // Prints 4.55
    System.out.println("Double to int: "+i); // Prints 4
    System.out.println("Float value: "+f); // Prints 1.25
    System.out.println("Float to int: "+i2); // Prints 1
  }
}

Output:

How To Type Casting In Java?

Widening Type Casting

An automated casting is widening type casting. A value of a smaller data type is assigned to a bigger size data type in this type casting. Implicit type casting is the term used when the compiler does the conversion without the need for the data type to be specified in parentheses.

public class JavaExample {
  public static void main(String[] args) {
    int i = 1001;
    float f = 105.00f;
    long l = i; // Implicit casting: int to long
    double d = f; // Implicit casting: float to double

    System.out.println("int Value: "+i); // Prints 1001
    System.out.println("int to long: "+l); // Prints 1001
    System.out.println("float value: "+f); // Prints 105.0
    System.out.println("float to double: "+d); // Prints 105.0
  }
}

Output:

How To Type Casting In Java?

Related Articles

Leave a Reply

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

Back to top button