Math Operations and Type Casting
Brew Bar splits a bill of 7 coffees between 2 friends and the till says each owes 3. Nobody pressed a wrong key: Java did exactly what the types asked for. Arithmetic in Java depends on the types of the numbers involved, and casting is how you change a type on purpose.
The rule
Int with int gives int; widen freely, narrow only with a cast.
The operators are the usual ones: +, -, *, /, and % for the remainder. The surprise is division. When both sides are whole numbers, / throws away the fraction:
int cups = 7;
System.out.println(cups / 2); // 3, not 3.5
System.out.println(cups % 2); // 1, the remainder
System.out.println(cups / 2.0); // 3.5, one side is a doubleIf either side is a double, Java does the calculation in double. That is widening: Java converts a smaller type into a bigger one automatically, along byte → short → int → long → float → double, because nothing important is lost.
Going the other way is narrowing, and Java makes you ask for it with a cast, a type in brackets:
double average = 3.99;
int whole = (int) average; // 3: the fraction is cut off, not rounded
long nearest = Math.round(average); // 4: rounding is a separate methodTwo more things behave differently from ordinary maths:
- The cast applies to what comes right after it.
(double) 7 / 2casts the 7 first, giving 3.5.(double) (7 / 2)divides first, giving 3, then widens to 3.0. - Whole numbers overflow silently.
Integer.MAX_VALUE + 1wraps around to a large negative number instead of failing. Uselongwhen totals could get big.
The Math class supplies the rest: Math.max(a, b), Math.min, Math.abs, Math.pow, Math.sqrt.
The shortcut
Before reading any result, write the type above each number, then apply the rule step by step. An int / int step always loses its fraction, even if the answer is stored in a double afterwards.
Label the types
int totalCents = 950;andint drinks = 4;are bothint.
Drills
Answer fast — trust the rule.
What does System.out.println(17 % 5); print?
int priceCents = 250; double dollars = priceCents / 100; What is dollars?
What is (int) 9.99?
Which expression evaluates to 3.5?
Which assignment needs an explicit cast to compile?
Remember
- Int with int gives int; widen freely, narrow only with a cast.
- Write the type over each number and work step by step.
- Traps:
(int)cuts rather than rounds, a cast binds to the very next value, and ints overflow silently.
