Operators in Java
Arithmetic, comparison, logical, and assignment operators, plus the gotchas around integer division and equality.
2 min read
Java's operators will look familiar if you've used any C-family language, but a couple of behaviors — especially around division and equality — surprise people coming from more forgiving languages.
Arithmetic operators
int sum = 5 + 3; // 8
int difference = 5 - 3; // 2
int product = 5 * 3; // 15
int quotient = 5 / 3; // 1 -- integer division truncates!
int remainder = 5 % 3; // 2Integer division truncates the decimal part entirely — 5 / 3 is 1, not 1.666.... To get a decimal result, at least one operand needs to be a floating-point type:
double result = 5.0 / 3; // 1.6666666666666667
double result2 = (double) 5 / 3; // same idea, cast one operand firstThis is one of the most common early bugs in Java: dividing two ints and being confused why the fractional part vanished.
Increment, decrement, and compound assignment
int count = 0;
count++; // count is now 1
count += 5; // count is now 6
count -= 2; // count is now 4x++ (post-increment) returns the value before incrementing; ++x (pre-increment) increments first, then returns it. This matters when the expression is used immediately: int a = 5; int b = a++; leaves b as 5 and a as 6, while int b = ++a; would leave both at 6.
Comparison and logical operators
boolean isEqual = (5 == 5); // true
boolean isGreater = (10 > 5); // true
boolean bothTrue = (true && false); // false
boolean eitherTrue = (true || false); // true
boolean negated = !true; // false&& and || short-circuit: in a() && b(), if a() returns false, b() never runs at all, because the overall result is already determined. This is used deliberately all the time to guard against errors:
if (list != null && !list.isEmpty()) {
// safe: if list is null, isEmpty() is never called
}== vs. .equals()
For primitives, == compares values directly, exactly as expected. For objects — including String — == compares whether two references point to the same object in memory, not whether their contents are equal.
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false -- different objects
System.out.println(a.equals(b)); // true -- same contentThis trips up nearly every Java beginner at least once. The rule: use == for primitives, and .equals() to compare the content of objects, including strings.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.