Java:Java Type Casting: Widening and Narrowing Conversions
Java•Type Casting

Java Type Casting: Widening and Narrowing Conversions

Learn how Java converts types automatically from smaller to larger primitives, and how to safely cast down.

Syntax

double d = 10; // Widening (automatic) int i = (int) 9.99; // Narrowing (explicit)

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
WideningConversionbyte -> short -> int -> long -> float -> double (safe).
NarrowingCastRequires explicit (target_type) cast; potential data loss.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    public static void main(String[] args) {
        // 1. Widening cast (automatic)
        int score = 95;
        double preciseScore = score;
        System.out.println("Widened double: " + preciseScore);

        // 2. Narrowing cast (explicit)
        double price = 49.95;
        int dollars = (int) price; // Truncates decimal
        System.out.println("Narrowed int:   " + dollars);

        // 3. String to number parsing
        int parsed = Integer.parseInt("2048");
        System.out.println("Parsed integer: " + (parsed + 2));
    }
}
Expected Output:
Widened double: 95.0
Narrowed int:   49
Parsed integer: 2050

How It Works: Step-by-Step

  • Lines 4-6: int score widens to double automatically without data loss.
  • Lines 9-11: Explicit (int) cast truncates 49.95 to 49.
  • Lines 14-15: Integer.parseInt converts numeric string to int.

Key Concepts

  • Java allows automatic widening because larger types can represent all values of smaller types.
  • Narrowing casts truncate decimals and can overflow if the value exceeds target type capacity.
  • Use Integer.parseInt() and Double.parseDouble() for string parsing.

Common Mistake: Expecting (int) 3.8 to round to 4

Narrowing casting truncates towards zero; it never rounds. Use Math.round() for rounding.

❌ Incorrect
int x = (int) 3.8; // Result is 3, not 4!
✅ Correct
int x = (int) Math.round(3.8); // Result is 4

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler