03 - Calculations
Calculations & Arithmetic
What is it?
Java supports standard math operations. You can use these in expressions, assign results to variables, or pass them directly to methods.
Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 3 + 2 |
5 |
- |
Subtraction | 5 - 1 |
4 |
* |
Multiplication | 4 * 3 |
12 |
/ |
Division | 7 / 2 |
3 ← integer! |
% |
Modulo (remainder) | 7 % 3 |
1 |
How does it work?
int sum = 5 + 3; // 8
int diff = 10 - 4; // 6
int prod = 3 * 4; // 12
int quot = 7 / 2; // 3 (NOT 3.5 - integer division truncates)
int rem = 7 % 3; // 1 (remainder after 7 ÷ 3 = 2, leftover 1)
Operator Precedence
Java follows standard math order of operations - BODMAS / PEMDAS:
- Parentheses
( )first - Then
*,/,%(left to right) - Then
+,-(left to right)
int result = 2 + 3 * 4; // 14, not 20 - multiplication first
int result = (2 + 3) * 4; // 20 - parentheses override
The Integer Division Trap
This is the #1 gotcha in arithmetic:
int a = 7 / 2; // Result: 3 (the .5 is silently dropped!)
double b = 7 / 2; // Still 3.0! - the division happens as int first
double c = 7.0 / 2; // 3.5 ← correct: one double forces double division
double d = (double) 7 / 2; // 3.5 ← casting to double
Warning If both operands are
int, the result is alwaysint- the decimal is truncated (not rounded). To get a decimal result, at least one operand must be adouble.
Modulo % - What’s it actually for?
Modulo gives you the remainder after division. It’s more useful than it looks:
// Is a number even or odd?
int n = 8;
if (n % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
// Wrap around (e.g., clock: after 23 comes 0)
int hour = (currentHour + 1) % 24;
Compound Assignment Operators
Shorthand for updating a variable:
| Shorthand | Equivalent |
|---|---|
x += 5 |
x = x + 5 |
x -= 3 |
x = x - 3 |
x *= 2 |
x = x * 2 |
x /= 4 |
x = x / 4 |
x++ |
x = x + 1 |
x-- |
x = x - 1 |
int score = 0;
score += 10; // score is now 10
score++; // score is now 11
Converting String Input to Numbers
User input always comes in as String. To do math with it:
Scanner scanner = new Scanner(System.in);
String raw = scanner.nextLine();
int number = Integer.parseInt(raw); // "42" → 42
double price = Double.parseDouble(raw); // "9.99" → 9.99
Gotchas
7 / 2=3, not3.5- integer division truncates silently%works on negative numbers too, but the result takes the sign of the dividend:-7 % 3 = -1- Dividing by zero (
n / 0) throwsArithmeticExceptionat runtime - guard against it
Related: String, Comparison, Condition