JavaType Casting

Java Type Casting

What Is Type Casting in Java?

Type casting in Java refers to converting a variable from one data type to another. This can happen automatically (by the compiler) or manually (by the programmer). It’s also called type conversion.

Common examples:

  • int to double

  • double to int

  • short to long

Types of Type Casting in Java

Type

Description

Performed By

Widening Casting

Converting smaller type to larger type

Compiler

Narrowing Casting

Converting larger type to smaller type

Programmer

Widening Type Casting (Implicit Conversion)

Widening casting happens automatically when a smaller data type is assigned to a larger one. No special syntax is needed.

Conversion Hierarchy

Text
byte → short → char → int → long → float → double

Example: Implicit Conversion

Java
public class WideningDemo {
    public static void main(String[] args) {
        int num1 = 5004;
        double num2 = 2.5;

        // int is automatically converted to double
        double result = num1 + num2;

        System.out.println("Sum: " + result);
    }
}
Sum: 5006.5
Note
Here, num1 (int) is implicitly converted to double before addition.
Type Conversion Error

If you try to assign a larger type to a smaller type without explicit casting, the compiler throws an error.

Example: Invalid Implicit Conversion

Java
public class ConversionErrorDemo {
    public static void main(String[] args) {
        int num1 = 5004;
        double num2 = 2.5;

        // Error: double cannot be assigned to int without casting
        int result = num1 + num2;

        System.out.println("Sum: " + result);
    }
}
Warning
Compilation Error: Type mismatch — cannot convert from double to int
Narrowing Type Casting (Explicit Conversion)

Narrowing casting is done manually using the cast operator. It’s required when converting a larger type to a smaller one.

Syntax

Java
targetType variable = (targetType) sourceVariable;

Example: Explicit Conversion

Java
public class NarrowingDemo {
    public static void main(String[] args) {
        int num = 5004;

        // Convert int to double
        double doubleValue = (double) num;
        System.out.println("Converted to double: " + doubleValue);

        // Convert double back to int
        int intValue = (int) doubleValue;
        System.out.println("Converted back to int: " + intValue);
    }
}
Converted to double: 5004.0
Converted back to int: 5004
Note
Explicit casting is safe when you’re sure the value fits in the target type.
Summary

Conversion Type

Direction

Automatic

Risk of Data Loss

Widening

Small → Large

Yes

No

Narrowing

Large → Small

No

Yes

Best Practices
Tip
Use widening casting when possible — it’s safer and automatic. Always check for possible data loss before narrowing. Use explicit casting only when you’re confident about the value range. Avoid narrowing between incompatible types (e.g., boolean to int).