Java does math with + - * / and the remainder operator %. This module has a few surprises — the first is how division behaves with whole numbers.
+ - * /
%
When both operands are int, / keeps only the whole part and drops the remainder — it does not round. So 7 / 2 is 3, not 3.5 and not 4.
int
/
7 / 2
3
3.5
4
System.out.println(7 / 2); // 3 System.out.println(30 / 4); // 7 System.out.println(24 / 4 / 2); // 3 (left to right: 6 / 2)
Run the code below — it prints 3. Now change 7 / 2 to 7 / 2.0 and run again: because one operand is a double, the result becomes 3.5. That one dot changes everything.
7 / 2.0
double
▶ Try it: run this, then change something and run it again.
What is 7 / 2 in Java?
Type exactly what this prints:
System.out.println(30 / 4);
What does 24 / 4 / 2 evaluate to?
24 / 4 / 2
True or false?