Course outline · 0% complete

0/29 lessons0%

Course overview →

Operators and casting

lesson 2-3 · ~7 min · 6/29

Arithmetic with a twist

Arithmetic looks too basic to study — until an average of test scores comes out as 79 instead of 79.5, or a discount computes to 0. Both are int-division bugs, and they ship to production every week somewhere. + - * / % work as in Python, with one big exception: dividing two ints throws away the remainder.

7 / 2    // 3, not 3.5
7 % 2    // 1, the remainder
7.0 / 2  // 3.5, because one side is a double

Python 3 gives you 3.5 for 7 / 2. Java behaves like Python's // when both sides are ints. If either side is a double, the result is a double.

Shortcuts you know from Python work too: x += 2, x -= 1, x *= 3. Java adds x++ (add 1) and x-- (subtract 1).

Code exercise · java

Run and compare the three division results. Only the version involving a double keeps the decimal part.

Casting

A cast converts a value to another type by writing the target type in parentheses:

int a = 7;
double d = (double) a / 2;  // 3.5, a becomes 7.0 first
int chopped = (int) 3.9;    // 3, decimals are cut off, not rounded

Going from int to double is safe and Java even does it automatically (double d = 7;). Going from double to int loses information, so Java forces you to write the cast explicitly. That is the theme of the whole language: anything lossy must be visible in the code.

Why money never goes in a double

A double stores numbers as binary fractions. Just as 1/3 has no exact decimal form (0.3333...), one tenth has no exact binary form — so 0.1 in a double is really a number extremely close to 0.1, and the tiny errors surface in arithmetic:

System.out.println(0.1 + 0.2);  // 0.30000000000000004

For physics or graphics the error is harmless. For money it is unacceptable — pennies must add up exactly. The industry-standard fix: store money as an int/long count of cents, do exact whole-number arithmetic, and only format as dollars when printing. Integer division and % from above are exactly the tools for that final formatting step.

Code exercise · java

Run this. First see the double error with your own eyes, then see the cents pattern: $10.99 plus $0.88 of tax, stored as ints, formatted with / and %.

Quiz

What does (int) 9.99 evaluate to?

Code exercise · java

Your turn. Convert 200 minutes into hours and minutes using integer division and %. Print exactly `3 h 20 min`. Then compute the exact decimal hours with a cast and print `3.3333333333333335 h` on the second line (just print totalMinutes divided by 60.0 concatenated with " h").