Part 02 / Topic 5 of 9
Type casting
Casting means converting a value from one type to another.
Widening (small type → big type) happens automatically, and never loses data:
int wholeRupees = 500;
double asDecimal = wholeRupees; // int -> double, no cast needed
Narrowing (big type → small type) needs an explicit cast (type), and can lose data:
double billAmount = 1299.99;
int truncated = (int) billAmount; // 1299 — cuts the decimal part, does NOT round
Output (examples/TypeCasting.java, first part):
500.0
1299
-1294967296
3
3.5
498
0.18
Quantity: 5
-1294967296 is what happens when a long holding 3,000,000,000 is narrowed to an int: the value is too big for int's range, so it wraps around to a meaningless number — silently, with no warning.
The classic trap: dividing two ints gives an int, even when you store the result in a double.
int total = 7;
int people = 2;
System.out.println(total / people); // 3 — already an int before it is printed
System.out.println((double) total / people); // 3.5 — cast ONE side BEFORE the division happens
Text ↔ number, the two directions you will use constantly:
int price = Integer.parseInt("249"); // String -> int
double gstRate = Double.parseDouble("0.18"); // String -> double
String asText = String.valueOf(5); // int -> String
parseInt/parseDouble do not guess. Bad text crashes the program on the spot, with no attempt to recover:
int broken = Integer.parseInt("12.5");
Real output (examples/TypeCasting.java, full run):
500.0
1299
-1294967296
3
3.5
498
0.18
Quantity: 5
Exception in thread "main" java.lang.NumberFormatException: For input string: "12.5"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at TypeCasting.main(TypeCasting.java:38)
Part 6 ("Exceptions basics") teaches try/catch to handle this gracefully. For now, just know that bad input text crashes the whole program — one more reason to double-check input before casting it.
Full program: examples/TypeCasting.java.
Done here? The practice set for Part 2 — including the solutions — is on the part page.