Math Operations and Type Casting
Arithmetic between two ints produces an int, Java widens smaller numeric types automatically, and narrowing to a smaller type needs an explicit cast.
Compare integer division with floating-point arithmetic and inspect narrowing conversions.
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.