- Prerequisites
- 2.3 Variables
- Covers
- Arithmetic · Relational · Logical · Bitwise · Assignment · Unary · Ternary · Shift · instanceof
- Related
- 3.4 Type Conversion · 3.5 Wrapper Classes · 6.3 Polymorphism (pattern matching)
On this page
1Concept / Definition
Operators combine operands into expressions that produce a value. Java's operators are familiar from C, but their exact rules — precedence, evaluation order, numeric promotion, short-circuiting and overflow — are specified precisely by the JLS and behave identically on every platform.

Java also guarantees left-to-right evaluation of operands: in f() + g(), f() is always called before g(). Precedence decides how an expression is grouped; evaluation order decides which operand runs first. Parentheses make both explicit and are preferred whenever an expression mixes operator groups.
2Why It Exists
Operators let code state a computation in the notation programmers already know from mathematics and from C. Java kept almost all of C's operators, so that C and C++ programmers could read it at once, but removed the parts that made C programs behave differently from one compiler or CPU to the next: every numeric type has a fixed size, integer overflow is defined to wrap, operands are evaluated left to right, and the result of each operator is specified exactly by the JLS.
Java also left some things out on purpose. Conditions must be boolean, so if (x = 5) is a compile error rather than a hidden assignment; there is no pointer arithmetic; and programmers cannot overload operators, so + means numeric addition or, with a String operand, concatenation, and nothing else. The traps that remain, such as silent overflow, compound-assignment narrowing and unboxing in ternaries, are the price of C compatibility and of autoboxing, and are the subject of sections 6 and 7.
3Core Concepts
Arithmetic
+ - * / % work on numeric types after binary numeric promotion: byte, short and char operands are promoted to int, and if either operand is long, float or double, the result has that wider type.
- Integer division truncates toward zero:
7 / 2 == 3,-7 / 2 == -3. %takes the sign of the dividend:-7 % 3 == -1.- Integer division by zero throws
ArithmeticException; floating-point division by zero givesInfinityorNaN. - Integer overflow wraps silently:
Integer.MAX_VALUE + 1 == Integer.MIN_VALUE. UseMath.addExactand friends when overflow must be detected. +with aStringoperand means concatenation, evaluated left to right:"Sum: " + 1 + 2gives"Sum: 12".
Relational
< > <= >= compare numeric values and produce a boolean. Comparisons involving NaN are always false, so x != x is true only when x is NaN.
Equality
== and != compare values for primitives and references (identity) for objects. Two different String objects with the same characters are not ==; use equals. Chapter 3 covers this in depth, including the wrapper-cache trap.
Logical
&& and || are short-circuit operators: the right operand is evaluated only if it can change the result. This is what makes user != null && user.isActive() safe. &, | and ^ applied to booleans always evaluate both operands, and ! negates.

Bitwise
& | ^ ~ operate on the individual bits of integer values: AND, OR, exclusive OR and complement. They are used for flags, masks, hashing and low-level protocols.

Shift
<< shifts left, filling with zeros (multiplying by powers of two until overflow). >> is an arithmetic right shift that keeps the sign bit, so -16 >> 2 == -4. >>> is a logical right shift that fills with zeros, so -16 >>> 2 is a large positive number. The shift distance is masked to the low 5 bits for int and 6 bits for long, so 1 << 32 == 1.
Assignment
= assigns and is itself an expression whose value is the assigned value. Compound assignments (+= -= *= /= %= &= |= ^= <<= >>= >>>=) include an implicit cast back to the variable's type: b += 300 compiles for a byte b, silently narrowing the result, whereas b = b + 300 does not compile.
Unary
Unary operators take one operand: + and - (sign), ++ and -- (increment and decrement), ! (logical not), ~ (bitwise complement) and casts. Prefix and postfix increments differ in which value the expression produces.

Ternary
condition ? a : b evaluates only one of a and b. The result type is computed from both branches, which leads to a classic trap: if one branch is int and the other Integer, the result type is int, and a null Integer is unboxed — throwing NullPointerException.
instanceof
obj instanceof Type tests whether a reference points to an object of that type (false for null). Since Java 16 it can bind a pattern variable: if (obj instanceof Invoice inv) both tests and casts. Record patterns (Java 21) can also deconstruct: if (shape instanceof Circle(double r)).
4How It Works Internally
javac evaluates an expression on the operand stack: it pushes the operands left to right and then emits one instruction per operator. Most operators map to a single bytecode, and the JIT maps most of those to a single CPU instruction. The table shows the translation for int operands unless stated otherwise:
| Source | Bytecode | What it explains |
|---|---|---|
| a + b, a * b | iadd, imul | No overflow check: the result wraps modulo 2^32 |
| a / b, a % b | idiv, irem | The JVM throws ArithmeticException when b is 0; the remainder has the sign of a |
| a << n, a >> n, a >>> n | ishl, ishr, iushr | Only the low 5 bits of n are used (6 for long) |
| x < y for double | dcmpg, then a jump | Any comparison with NaN takes the false branch |
| b += 300 for a byte | iadd, then i2b | The hidden narrowing cast of compound assignment |
| i++ on a local int | iinc | Increments the slot in place, no load or store |
| a && b, a || b | conditional jumps | There is no AND instruction; the right side is skipped by a jump |
| "Total: " + n | invokedynamic | StringConcatFactory builds the string (Java 9+) |

5APIs / Features / Syntax
The operators are fixed, but java.lang.Math, the wrapper classes and Objects add the operations that the operators leave out or get wrong for business code:
| Method | Use it for |
|---|---|
| Math.addExact, subtractExact, multiplyExact, toIntExact | Arithmetic that must throw on overflow instead of wrapping |
| Math.floorDiv, Math.floorMod | Division and remainder rounded towards negative infinity: a bucket or index that is never negative |
| Math.absExact (Java 15), Math.clamp (Java 21) | abs that throws for MIN_VALUE; limiting a value to a range |
| Integer.compare, Long.compare | Comparators without the overflow of a - b |
| Integer.bitCount, toBinaryString, numberOfTrailingZeros | Counting and inspecting bits for flags and masks |
| Integer.divideUnsigned, compareUnsigned, toUnsignedString | Treating an int as unsigned, for protocols and hashes |
| Objects.equals(a, b) | Null-safe equality instead of == on objects |
6Practical Examples
Example 1 — Arithmetic, concatenation and compound-assignment traps
System.out.println(7 / 2); // 3
System.out.println(-7 % 3); // -1
System.out.println(7.0 / 0); // Infinity
System.out.println(Integer.MAX_VALUE + 1); // -2147483648 (silent overflow)
System.out.println(Math.addExact(Integer.MAX_VALUE, 1)); // ArithmeticException
System.out.println("Sum: " + 1 + 2); // Sum: 12
System.out.println("Sum: " + (1 + 2)); // Sum: 3
System.out.println(1 + 2 + " items"); // 3 items
byte b = 10;
b += 300; // compiles: (byte)(10 + 300) = 54
// b = b + 300; // compile error: int to byteEvery comment shows what the line really prints (kit class OperatorTraps). Compiled with -Xlint:all, javac 20 and later also warns about b += 300: "implicit cast from int to byte in compound assignment is possibly lossy".
Example 2 — Mini program: a daily sales total that overflows
Problem. A reporting job adds up a day's orders in paise, the minor unit, to avoid floating point. With 30,000 orders of Rs 1,234.56 the total no longer fits in an int. The program compares the int, long, addExact, double and BigDecimal approaches on the same data.
import java.math.BigDecimal;
import java.util.Arrays;
public class OrderTotals {
public static void main(String[] args) {
int[] paise = new int[30_000]; // 30,000 orders of Rs 1,234.56
Arrays.fill(paise, 123_456); // minor units (paise)
int intTotal = 0;
long longTotal = 0;
for (int p : paise) {
intTotal += p; // wraps past 2^31 - 1
longTotal += p; // promoted to long: exact
}
System.out.println("int total : " + intTotal);
System.out.println("long total : " + longTotal);
try {
int checked = 0;
for (int p : paise) checked = Math.addExact(checked, p);
} catch (ArithmeticException e) {
System.out.println("addExact : " + e.getMessage());
}
double rupees = 0;
BigDecimal exact = BigDecimal.ZERO;
for (int i = 0; i < 10; i++) { // ten items at Rs 0.10
rupees += 0.10;
exact = exact.add(new BigDecimal("0.10"));
}
System.out.println("double sum : " + rupees);
System.out.println("BigDecimal sum : " + exact);
BigDecimal report = BigDecimal.valueOf(longTotal, 2); // rupees
System.out.println("report : Rs " + report);
int n = paise.length;
System.out.println("average : " + longTotal / n / 100
+ " (integer division) vs " + longTotal / (double) n / 100);
}
}int total : -591287296
long total : 3703680000
addExact : integer overflow
double sum : 0.9999999999999999
BigDecimal sum : 1.00
report : Rs 37036800.00
average : 1234 (integer division) vs 1234.56Why it behaves this way. The true total, 3,703,680,000 paise, is above Integer.MAX_VALUE (2,147,483,647), so intTotal wraps by 2^32 to a negative number without any error. In longTotal += p the int is promoted to long before the addition, so the sum is exact. Math.addExact throws at the first addition that would wrap, which is the right behaviour for a job that must never report a wrong figure. Ten additions of 0.10 in double give 0.9999999999999999 because 0.1 has no exact binary representation, while BigDecimal keeps 1.00. The last line shows a quieter bug: long / int is integer division, so the paise of the average are lost before anything is printed.
Example 3 — The ternary unboxing trap
Map<String, Integer> stock = Map.of("pen", 5);
int ok = stock.containsKey("book") ? stock.get("book") : 0; // safe
Integer n = flag ? stock.get("book") : 0; // NPE when flag is true:
// branches are Integer and int, so the result type is int and null is unboxedExample 4 — Bit flags and pattern matching with instanceof
int READ = 1, WRITE = 1 << 1, EXEC = 1 << 2; // 001, 010, 100
int perms = READ | WRITE; // 011
boolean canWrite = (perms & WRITE) != 0; // true
perms &= ~WRITE; // clear WRITE -> 001
if (payment instanceof CardPayment card && card.amount() > 1_000) {
requireStrongAuthentication(card);
}Example 5 — Picking a shard: % versus Math.floorMod
Problem. A service spreads customers over three database shards with id.hashCode() % shards. Some requests fail with ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3. The program shows the three common formulas side by side.
public class ShardPicker {
public static void main(String[] args) {
int shards = 3;
String[] ids = {"C-1001", "customer-42", "polygenelubricants"};
System.out.printf("%-19s %12s %4s %9s %9s%n",
"id", "hashCode", "%", "abs, %", "floorMod");
for (String id : ids) {
int h = id.hashCode();
System.out.printf("%-19s %12d %4d %9d %9d%n", id, h,
h % shards, // sign of the dividend
Math.abs(h) % shards, // abs(MIN_VALUE) < 0
Math.floorMod(h, shards)); // always 0 .. shards - 1
}
}
}id hashCode % abs, % floorMod
C-1001 1961218986 0 0 0
customer-42 -1772111155 -1 1 2
polygenelubricants -2147483648 -2 -2 1Why it behaves this way. hashCode() is negative for about half of all strings, and % keeps the sign of the dividend, so customer-42 maps to shard -1. Math.abs looks like the fix but fails for one value: the hash code of polygenelubricants is Integer.MIN_VALUE, whose absolute value does not fit in an int, so Math.abs returns it unchanged and the result is still negative. Math.floorMod rounds towards negative infinity and always returns 0, 1 or 2 for a positive divisor (Figure 6).

7Common Problems & Mistakes
| Mistake | Result | Fix |
|---|---|---|
| == on Strings or wrappers | Compares identity; works by accident sometimes | Use equals (or Objects.equals) |
| Silent integer overflow in money or counters | Wrong totals, negative values | long, Math.*Exact, or BigDecimal for money |
| Floating point for money | 0.1 + 0.2 != 0.3 | BigDecimal with explicit scale and rounding |
| & instead of && in null checks | Right side evaluated, NullPointerException | Use short-circuit operators |
| Mixing int and Integer in a ternary | NullPointerException from unboxing | Make both branches the same type |
| Relying on precedence in complex expressions | Hard to read, easy to get wrong | Add parentheses |
| x = x++ | x is unchanged | Use x++ or x += 1 |
| hashCode() % n as an index or shard | Negative for half of all hash codes; Math.abs does not help for MIN_VALUE | Math.floorMod(h, n) (Example 5) |
| double avg = sum / count with integer operands | The fraction is lost before the conversion to double | Divide in double: sum / (double) count |
| Printing char arithmetic: 'A' + 1 | Prints 66: char operands are promoted to int | Cast back, (char) ('A' + 1), or use Character methods |
| Comparators written as a - b | Overflows for large or negative values and breaks the sort order | Integer.compare(a, b) or Comparator.comparingInt |
8Performance & Production Considerations
- Operators themselves are cheap; the JIT maps them directly to CPU instructions and replaces, for example, multiplication by a power of two with a shift. Writing shifts by hand for speed is rarely worth the readability cost.
- String concatenation with
+is compiled to an efficientinvokedynamiccall since Java 9; in loops that build large strings, useStringBuilder. - Overflow bugs are production bugs, not performance issues: counters, IDs and time arithmetic in
intare the usual suspects.
9Architecture & Design Considerations
Operator choices can encode domain rules. Money should be BigDecimal or an integer number of minor units, never double. Identifiers and counters that can grow over a system's lifetime should be long. Equality of domain objects should be defined by equals, not by ==. These are small decisions at code level, but they become data-integrity issues at system level and are worth stating in coding standards.
10Interview Questions & Answers
What is the difference between && and &?
&& is the logical AND with short-circuit evaluation: if the left side is false, the right side is not evaluated. & on booleans always evaluates both sides, and on integers performs a bitwise AND. That is why user != null && user.isActive() is safe and the same test with & throws NullPointerException when user is null.
What is the difference between >> and >>>?
>> is an arithmetic right shift: it preserves the sign bit, so negative numbers stay negative. >>> is a logical right shift: it fills with zeros, so a negative number becomes a large positive one. For non-negative numbers they give the same result. For example, -16 >> 2 is -4 and -16 >>> 2 is 1073741820; >>> is what hash functions and unsigned arithmetic need.
What does "Sum: " + 1 + 2 print, and why?
Sum: 12. + is left-associative; once the left operand is a String, each following + is concatenation. Parentheses — "Sum: " + (1 + 2) — force numeric addition first.
Why does byte b = 10; b += 300; compile but b = b + 300; does not?
In b + 300, b is promoted to int and the result is int, which cannot be assigned to a byte without a cast. A compound assignment includes an implicit cast to the variable's type, so b += 300 compiles and silently narrows the result to 54.
How can a ternary expression throw NullPointerException?
When one branch has a primitive type and the other its wrapper type, the result type is the primitive, so the wrapper value is unboxed. If it is null, unboxing throws NullPointerException. Keeping both branches the same type avoids this.
A daily counter stored as an int started returning negative values after months in production. Explain and fix.
The value exceeded Integer.MAX_VALUE and wrapped around; Java integer arithmetic overflows silently. Use long for counters and identifiers that can grow over the system's lifetime, and Math.addExact where overflow must be detected rather than tolerated. A long counter incremented a million times per second takes about 290,000 years to overflow.
What coding-standard rules about operators and numeric types would you set for a financial platform?
Use BigDecimal (or integer minor units) for money with explicit scale and rounding; forbid float/double for monetary values; use long for identifiers and counters; compare objects with equals, never ==; use exact-arithmetic methods where overflow must fail loudly; and require parentheses in mixed-operator expressions. Enforce them with static analysis so they do not depend on code review alone.
What is the difference between operator precedence and evaluation order?
Precedence decides how an expression is grouped: a + b * c means a + (b * c). Evaluation order decides when each operand is computed, and Java fixes it as left to right: a, then b, then c, whatever the grouping. The two only matter together when operands have side effects, such as method calls or ++. C leaves the order of operand evaluation largely unspecified; Java defines it, so the same expression gives the same result on every JVM.
What does this program print?
public class CharMath {
public static void main(String[] args) {
char c = 'A';
System.out.println(c + 1);
System.out.println((char) (c + 1));
System.out.println("" + c + 1);
c += 1;
System.out.println(c);
}
}It prints 66, B, A1, B. c + 1 promotes the char to int, so the result is the number 66; the cast turns it back into the character B. In "" + c + 1, the left operand is a String, so both + are concatenations. c += 1 compiles without a cast because compound assignment narrows the result back to char.
What does this program print?
import java.util.Arrays;
public class EvalOrder {
static int trace(String name, int value) {
System.out.print(name + " ");
return value;
}
public static void main(String[] args) {
int r = trace("a", 1) + trace("b", 2) * trace("c", 3);
System.out.println("= " + r);
int i = 1;
i = i++ + ++i;
System.out.println(i);
int[] arr = {0, 0};
int j = 0;
arr[j] = j = 1;
System.out.println(Arrays.toString(arr));
}
}It prints a b c = 7, 4, [1, 0]. The operands are evaluated left to right, a b c, even though the multiplication is done first. In i = i++ + ++i, the left operand is 1 (and i becomes 2), the right operand increments i to 3 and yields 3, so i is assigned 4. In arr[j] = j = 1, the array index is evaluated before the right-hand side, so arr[0] receives 1. Code like this compiles and is well defined, but it should never pass a review.
Why can Math.abs return a negative number?
Math.abs(Integer.MIN_VALUE) is Integer.MIN_VALUE, -2,147,483,648, because +2,147,483,648 does not fit in an int: negating the value overflows and wraps back to itself. It matters wherever Math.abs is used to make a value non-negative, as in Math.abs(hash) % n (Example 5). Use Math.floorMod for indexes, or Math.absExact, which throws ArithmeticException instead of returning a negative result.
How are && and string concatenation with + compiled?
&& and || have no bytecode instruction of their own. javac compiles them into conditional jumps: if the left side of && is false, a jump skips the right side, which is what short-circuiting means (Figure 5). String concatenation has been compiled to a single invokedynamic instruction since Java 9; at first call StringConcatFactory generates the code that builds the string, so the JDK can improve the strategy without recompiling applications. Inside a loop that builds one large string, StringBuilder is still better, because each + creates a new String.
Requests for some customers fail with ArrayIndexOutOfBoundsException: Index -1 in a shard router that uses customerId.hashCode() % shardCount. Diagnose it and fix it properly.
hashCode() can be negative and % keeps the sign, so negative hashes produce negative shard numbers; the customers affected are always the same ones, which is why the failure looks random but is reproducible. Replace the formula with Math.floorMod(hash, shardCount) and add a test with a negative and a MIN_VALUE hash. Then check the design: with modulo routing, changing the shard count moves almost every customer, so a system that will grow should use consistent hashing or a lookup table, and should hash with a stable function rather than String.hashCode if other languages must compute the same shard.
For a multi-currency payments platform, would you represent money as double, as long minor units or as BigDecimal?
Never double: it cannot represent most decimal fractions, so totals drift and comparisons fail. long minor units are exact, fast, compact in databases and messages, and safe from overflow for any realistic amount, but the number of decimals differs by currency (0 for JPY, 2 for INR, 3 for KWD), so every value must travel with its currency and scale, and rates or interest need more precision. BigDecimal handles any scale and explicit rounding modes at the cost of allocation and slower arithmetic. A common split is a Money value type with an amount and a currency inside the domain, stored and transmitted as minor units plus an ISO currency code, and BigDecimal for calculations such as FX conversion, with the rounding rule stated in one place.
Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Precedence groups an expression; operands are always evaluated left to right.
- Integer overflow wraps silently; integer division truncates; floating point cannot represent money exactly.
- && and || short-circuit; & and | do not.
- Compound assignments hide a narrowing cast; ternaries can hide unboxing.
- instanceof with patterns tests and casts in one step.