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:
| Parameter | Type | Description |
|---|---|---|
| Widening | Conversion | byte -> short -> int -> long -> float -> double (safe). |
| Narrowing | Cast | Requires explicit (target_type) cast; potential data loss. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java Variables and Primitive Data Types with Examples
Declare typed variables in Java including int, double, boolean, String, and local var (Java 10+).
Java Operators: Arithmetic, Logical, and Bitwise
Explore arithmetic (+, -, *, /, %), relational, and logical (&&, ||, !) operators in Java.
Java If...Else and Ternary Conditional Statements
Implement decision-making logic using if, else if, else, and ternary operators.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.