Arithmetic Operators in Java
Java has seven arithmetic operators: +, -, *, /, %, ++, --. They operate on numeric types (byte, short, int, long, float, double, char). + is also the string-concatenation operator when either operand is a String.
Basics
int a = 10, b = 3;
a + b; // 13
a - b; // 7
a * b; // 30
a / b; // 3 β integer division truncates
a % b; // 1 β remainder
Integer vs floating division
7 / 2; // 3 β both operands int
7 / 2.0; // 3.5 β at least one double β double result
(double) 7 / 2; // 3.5 β explicit cast
7 % 2; // 1
7.5 % 2; // 1.5 β remainder works on floats too
Increment and decrement
int i = 5;
int a = i++; // post-increment: a = 5, i = 6
int b = ++i; // pre-increment: b = 7, i = 7
int c = i--; // post-decrement
int d = --i; // pre-decrement
In isolation they behave the same (i++ alone just increments). In an expression, the pre/post distinction matters.
Overflow
int m = Integer.MAX_VALUE;
m + 1; // wraps to Integer.MIN_VALUE β no exception
Math.addExact(m, 1); // β
throws ArithmeticException
String concatenation
"result: " + 1 + 2; // "result: 12" β left-to-right, string wins
1 + 2 + " = sum"; // "3 = sum" β ints first, then joined
"a" + null; // "anull" β null is stringified
"a" + (char) 65; // "aA" β char is widened to String via Character
Always parenthesise the non-string part when mixing: "result: " + (a + b).
Compound assignment
x += 5; // x = x + 5
x -= 3; // x = x - 3
x *= 2;
x /= 4;
x %= 3;
Compound operators include an implicit cast: byte b = 1; b += 0.5; compiles (cast to byte), while b = b + 0.5; does not.
Common mistakes
- Integer division surprise β
5 / 2is2, not2.5. - Silent overflow in large products β multiply as
longfrom the start. i += 1vs++iβ equivalent for primitives, but++ion anAtomicIntegerdoesn't exist; useincrementAndGet().- String concatenation order β
"a" + 1 + 2is"a12", not"a3".
Related
Pillar: Java operators. See also int, double.