Type Conversion and Casting

In Java, type conversion and casting are used to change one data type into another. This is helpful when you need to perform operations that involve different data types. There are two main ways to do this: automatic (implicit) conversion and manual (explicit) casting.

1. Automatic (Implicit) Type Conversion

Automatic conversion happens when Java converts one data type to another type automatically. This usually happens when you're working with compatible types, and there’s no risk of losing information.

For example:

int can be automatically converted to double because double can hold a larger range of values.

Java
Copy
int num = 10;
double newNum = num;  // Automatic conversion from int to double
System.out.println(newNum);  // Output: 10.0

Java can automatically convert smaller types to larger types in this order:

byte > short > int > long > float > double

Manual (Explicit) Type Casting

When you need to convert a larger data type to a smaller one (like double to int), Java requires you to cast the value manually. This is called explicit casting because it may lead to data loss (e.g., losing decimal points).


To cast a value, put the target type in parentheses before the value.

Java
Copy
double num = 10.5;
int newNum = (int) num;  // Casting from double to int
System.out.println(newNum);  // Output: 10 (decimal part is lost)

Examples of Type Conversion and Casting

Here’s a simple program showing both implicit and explicit conversions:

Java
Copy
public class TypeConversionExample {
    public static void main(String[] args) {
        // Implicit Conversion
        int intNum = 50;
        double doubleNum = intNum;  // Automatic conversion from int to double
        System.out.println("Double value: " + doubleNum);  // Output: 50.0

        // Explicit Casting
        double decimalNum = 9.99;
        int intResult = (int) decimalNum;  // Manual casting from double to int
        System.out.println("Integer value: " + intResult);  // Output: 9
    }
}