Type Casting & Conversion
Prerequisites: Variables & data types
Converting between numeric types is either automatic (widening, no data can be lost) or must be requested explicitly (narrowing, data can be lost):
int whole = 42;
double asDouble = whole; // widening: automatic, safe
double price = 19.99;
int asInt = (int) price; // narrowing: explicit cast required
System.out.println(asInt); // 19 — the decimal part is discarded
Converting between String and numbers uses the wrapper classes, not
a cast:
String text = "42";
int parsed = Integer.parseInt(text); // String -> int
String back = String.valueOf(parsed); // int -> String
Common mistakes
- Assuming
(int) pricerounds — it truncates.19.99becomes19, not20. UseMath.round(price)to round instead. - Calling
Integer.parseInt()on text that isn't a valid number throws aNumberFormatException.