Java Type Casting & Conversion
Type casting is when you assign a value of one primitive data type to another type. Java supports Widening Casting (automatic) when moving to a larger type, and Narrowing Casting (manual) when moving to a smaller type where data loss could occur.
"Widening casting is pouring a small glass of water into a giant bucket: nothing spills. Narrowing casting is pouring a giant bucket into a small cup: you must manually confirm and accept that excess water will overflow."
Deep Dive: How It Works
Widening Casting (Automatic): byte -> short -> char -> int -> long -> float -> double. Safe, no precision loss.
Narrowing Casting (Explicit): double -> float -> long -> int -> char -> short -> byte. Requires explicit syntax `(type) value`.
String conversion: `Integer.parseInt("123")`, `Double.parseDouble("45.67")`, `String.valueOf(100)`.
Syntax Blueprint
int myInt = 9; double myDouble = myInt; // Widening (automatic) int backToInt = (int) myDouble; // Narrowing (manual)
Place target type in parentheses for manual narrowing cast: (int) 3.99 becomes 3.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Assuming (int) rounds up or down: (int) 7.89 yields 7Why it happens: Narrowing cast simply chops off the decimal digits.
How to fix: Use Math.round(7.89) if you want standard rounding before casting.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Convert string price to int cents
Parse the string "25.75" into a double named "price".
Calculate total cents: (int) (price * 100).
Print "Cents: " + cents.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.