Mastering data conversion, navigating the limits of memory, and writing efficient shortcuts.
Why can't we just assign a double to an int?
double holds more information than an int. Java refuses to silently lose that data. Changing types: Narrowing vs. Widening
double → intint → double(int) someDoubleCasting cuts the decimal — it never rounds
What is the value of result?
How to achieve (nearest int) instead of just truncation
0.5 before casting. (int)(x + 0.5)0.5 before casting. (int)(x - 0.5)What happens when you exceed the limit?
-2,147,483,6482,147,483,647What does this print?
Why doubles are sometimes 'approximate'
Some decimal values cannot be stored exactly as doubles. Java keeps a very close approximation instead.
This leads to tiny precision errors during calculation. Never use == to compare doubles!
Predict the output
Write less, mean the same — each line starts from xp = 10
x op= y is always equivalent to x = x op y. What is the result?
The ultimate one-step shortcut
x = x + 1.x = x - 1.What is the final value?
The four things you must remember
(int) 3.9 → 3 (truncation, not rounding)
Integer.MAX_VALUE + 1 wraps to MIN_VALUE (Overflow)
0.1 + 0.2 can equal 0.30000000000000004 (Round-off Error)
x += 5 (compound) and x++ (increment) save time
double.int and print values.*= to add a discount.int score = 0.+=.*=.-=.