Java - Operators
Operators
Arithmetic
int a = 5 + 2; int b = a - 3; int c = a * b; int d = a / b; int r = a % b;
Integer division truncates toward zero. Use double
for floating-point division.
Comparison
boolean ok = (a > 3) && (a < 10);
Logical
&&
and ||
short-circuit; &
and |
always evaluate both operands.
Bitwise and Shift
int flags = 0b0101;
int setMask = 0b0010;
flags |= setMask; // set bit
boolean isSet = (flags & setMask) != 0;
int shifted = flags << 1;
Assignment and Compound
int x = 0; x += 5; x *= 2;
Equality: == vs equals()
==
compares primitives by value and references by identity. For strings and most objects, use equals()
.
String s1 = new String("hi");
String s2 = new String("hi");
boolean sameRef = (s1 == s2); // false
boolean sameVal = s1.equals(s2); // true
Precedence and Associativity
When in doubt, add parentheses to make intent explicit.
int v = 1 + 2 * 3; // 7 (multiplication before addition)
int w = (1 + 2) * 3; // 9
Numeric Promotion
Mixed-type arithmetic promotes smaller types to larger (e.g., int
to long
, long
to double
).
Pitfall: Beware of overflow in integer arithmetic. Use
Math.addExact
et al. to detect overflow where needed.Try it
- Evaluate
1 + 2 * 3
vs(1 + 2) * 3
and explain precedence. - Use
==
vsequals()
on two distinct but equal strings. - Manipulate bit flags: set, clear, and toggle a bit.