Java Type Casting

Type Casting in Java

Type casting in Java refers to the process of converting a value from one data type to another. It is essential because Java is a strongly typed language, meaning that variables must have a declared type, and operations between different data types often require explicit conversion.

Implicit vs. Explicit Casting: Implicit casting (widening) occurs when a smaller data type is automatically converted into a larger data type. Explicit casting (narrowing) involves manually converting a larger data type into a smaller one, and it may result in data loss.

In Java, you can cast between primitive data types. There are two main types of casting:

  • Widening (Automatic) Casting: This happens when you convert a smaller data type to a larger one. Java handles this automatically as it poses no risk of data loss. For example, casting an int to a double is implicit.
Example
public class Main {
  public static void main(String[] args) {
    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double

    System.out.println(myInt);      // Outputs 9
    System.out.println(myDouble);   // Outputs 9.0
  }
}
  • Narrowing (Explicit) Casting: This is the manual conversion of a larger data type to a smaller one. It should be used cautiously as it may lead to data truncation or loss. For example, casting a double to an int requires explicit casting.
Example
public class Main {
  public static void main(String[] args) {
    double myDouble = 9.78d;
    int myInt = (int) myDouble; // Manual casting: double to int

    System.out.println(myDouble);   // Outputs 9.78
    System.out.println(myInt);      // Outputs 9
  }
}

Contact Us

Name
Email
Mobile No:
subject:
Message: