Java Operators
A complete walkthrough of every operator category in Java: arithmetic, assignment, comparison, logical, bitwise, ternary, instanceof, and the rules of precedence that determine how expressions are evaluated.
Arithmetic Operators
Arithmetic operators perform mathematical operations on numeric values. Java supports the five standard operators you would expect from any programming language, but a few of them have subtleties worth understanding before you rely on them in real code.
The five arithmetic operators
All five work on both integer and floating-point types. Their behaviour differs slightly depending on which type is involved.
- + (Addition):Adds two values. Also acts as the string concatenation operator when either operand is a String.
- - (Subtraction):Subtracts the right operand from the left.
- * (Multiplication):Multiplies two values.
- / (Division):Divides the left operand by the right. When both operands are integers, the result is truncated (not rounded): 7 / 2 gives 3, not 3.5.
- % (Modulus / Remainder):Returns the remainder after integer division: 17 % 5 gives 2. Works with floating-point values too: 5.5 % 2.0 gives 1.5.
Integer division and the modulus gotcha
These two behaviours trip up almost every beginner at least once.
- Integer division truncates toward zero: -7 / 2 is -3 in Java, not -4.
- Modulus preserves the sign of the left operand: -7 % 3 is -1, not 2.
- Division by zero with integers throws ArithmeticException at runtime.
- Division by zero with doubles produces Infinity or NaN, not an exception.
Arithmetic Operators in Action
JavaInteger division, modulus, string concatenation with +, and floating-point edge cases.
Increment and Decrement Operators
The ++ and -- operators add or subtract 1 from a variable. That part is simple. What confuses most beginners is the difference between the prefix and postfix forms. Both modify the variable, but they differ in what value the expression itself evaluates to when used inside a larger statement.
Prefix vs. postfix: the key difference
The distinction only matters when you use the expression's value. As standalone statements (on their own line), ++x and x++ are identical.
- Prefix (++x or --x):Increments or decrements first, then returns the new value. The expression ++x where x is 5 evaluates to 6.
- Postfix (x++ or x--):Returns the original value first, then increments or decrements. The expression x++ where x is 5 evaluates to 5, and then x becomes 6.
Prefix vs. Postfix Increment
JavaThe value returned by the expression is the key difference between prefix and postfix.
Assignment Operators
The simple assignment operator = copies the value of the right-hand side into the variable on the left. Java also provides compound assignment operators that combine an arithmetic or bitwise operation with assignment into a single, more concise expression. Beyond saving keystrokes, compound operators have a subtle advantage: they include an implicit cast back to the left-hand type, which matters when mixing types.
Standard compound assignment operators
Each operator combines an operation with assignment. x += 5 is shorthand for x = x + 5.
- +=Add and assign: x += 3 is x = x + 3
- -=Subtract and assign: x -= 3 is x = x - 3
- *=Multiply and assign: x *= 3 is x = x * 3
- /=Divide and assign: x /= 3 is x = x / 3
- %=Modulus and assign: x %= 3 is x = x % 3
The implicit cast advantage
Compound operators include an implicit narrowing cast that the expanded form does not.
- byte b = 10; b += 5; compiles fine.
- byte b = 10; b = b + 5; is a compiler error: b + 5 promotes to int, and you cannot assign an int back to a byte without an explicit cast.
- The compound form b += 5 inserts the cast automatically, equivalent to b = (byte)(b + 5).
Assignment and Compound Assignment
JavaAll five compound arithmetic assignments demonstrated with their output.
Compound Assignment with Bitwise Operators
Java provides compound assignment versions of all four bitwise operators and both shift operators. They follow the exact same pattern as the arithmetic compound assignments: they apply the operation and assign the result back to the variable in one step. These appear frequently in low-level code, performance-critical algorithms, and flag manipulation.
Bitwise compound assignment operators
Each combines a bit-level operation with assignment.
- &=Bitwise AND and assign: x &= mask clears bits in x that are 0 in mask
- |=Bitwise OR and assign: x |= flag sets specific bits in x
- ^=Bitwise XOR and assign: x ^= toggle flips specific bits in x
- <<=Left-shift and assign: x <<= 2 multiplies x by 4 using shifts
- >>=Signed right-shift and assign: x >>= 1 divides x by 2 preserving sign
Bitwise Compound Assignments
JavaFlag manipulation and shift-based operations using compound assignment.
Comparison Operators
Comparison operators compare two values and return a boolean: either true or false. They are the foundation of every conditional statement and loop condition you will ever write. The most important rule to internalise early: use == for primitive comparison only. For objects, including String, use .equals().
The six comparison operators
All six return a boolean result and work on numeric primitives directly.
- == (Equal to):Returns true if both operands have the same value. For primitives, compares values. For objects, compares references (memory addresses), not contents.
- != (Not equal to):Returns true if the operands differ.
- < (Less than):Returns true if the left operand is strictly less than the right.
- > (Greater than):Returns true if the left operand is strictly greater than the right.
- <= (Less than or equal to):Returns true if the left operand is less than or equal to the right.
- >= (Greater than or equal to):Returns true if the left operand is greater than or equal to the right.
== on objects vs. .equals()
This is one of the most common sources of bugs for Java beginners. The == operator on Strings compares references, not the actual text content.
- String a = "hello"; String b = "hello"; a == b may be true due to string interning, but this behaviour is an implementation detail you should not rely on.
- String a = new String("hello"); String b = new String("hello"); a == b is always false because they are two different objects.
- Always use a.equals(b) to compare the content of String objects.
- The same rule applies to all reference types: Integer, List, and any class you create.
Comparison Operators
JavaAll six operators on primitives, plus the == vs. equals() demonstration on Strings.
Logical Operators
Logical operators combine boolean expressions. They are the core tool for writing conditions that depend on more than one factor: "if the user is logged in AND has permission" or "if the input is null OR empty." Java provides three logical operators, and the short-circuit behaviour of two of them is not just a performance detail; it is an important defensive programming technique.
The three logical operators
&& and || use short-circuit evaluation. The bitwise & and | do not.
- && (Logical AND):Returns true only if both operands are true. Short-circuits: if the left operand is false, the right operand is never evaluated.
- || (Logical OR):Returns true if at least one operand is true. Short-circuits: if the left operand is true, the right operand is never evaluated.
- ! (Logical NOT):Inverts a boolean value. !true gives false; !false gives true.
Short-circuit evaluation: why it matters
Short-circuit evaluation is a feature, not a side effect. You can deliberately use it to guard against errors.
- if (obj != null && obj.getValue() > 0): the right side is never reached if obj is null, preventing a NullPointerException.
- if (list == null || list.isEmpty()): the right side is never reached if list is null, preventing a NullPointerException on isEmpty().
- Short-circuiting also means method calls on the ignored side are never executed, which can affect program state if those methods have side effects.
- Use & and | (bitwise) only when you explicitly need both sides evaluated regardless of the result.
Logical Operators and Short-Circuit Evaluation
JavaAll three logical operators with a null-guard pattern demonstrating short-circuit evaluation.
Bitwise Operators
Bitwise operators work directly on the binary representation of integer values. They process each bit of the operand independently. While they appear less often in everyday business logic, they are essential in areas like permissions and flags, cryptography, network protocol parsing, graphics, and performance-sensitive code where multiplying or dividing by powers of two using shifts is faster than the arithmetic operation.
The four bitwise logical operators
Each operates on corresponding pairs of bits between two operands.
- & (Bitwise AND):Result bit is 1 only if both input bits are 1. Use to mask (clear) specific bits: value & 0xFF extracts the lowest 8 bits.
- | (Bitwise OR):Result bit is 1 if either input bit is 1. Use to set specific bits: flags | 0x04 sets bit 2.
- ^ (Bitwise XOR):Result bit is 1 if the input bits differ. Use to toggle specific bits. XOR-ing a value with itself always gives 0.
- ~ (Bitwise NOT / Complement):Flips every bit. ~5 gives -6 in a 32-bit signed integer because of two's complement representation.
The three shift operators
Shift operators move all bits left or right by a specified number of positions.
- << (Left shift):Shifts bits left, filling vacated bits with 0. Equivalent to multiplying by 2 for each position shifted: x << 3 is x * 8.
- >> (Signed right shift):Shifts bits right, filling vacated bits with the sign bit (0 for positive, 1 for negative). Equivalent to dividing by 2, preserving the sign.
- >>> (Unsigned right shift):Shifts bits right, always filling vacated bits with 0 regardless of sign. Useful when working with raw bit patterns rather than signed numbers.
Bitwise and Shift Operators
JavaMasking, setting, toggling bits, and shift-based multiplication and division.
Ternary Operator
The ternary operator is Java's only operator that takes three operands. It provides a compact way to write a simple if-else expression on a single line. The syntax is: condition ? valueIfTrue : valueIfFalse. The entire expression evaluates to one of the two values depending on whether the condition is true or false.
When to use the ternary operator
Ternary is best suited for simple, single-value selections. Anything more complex deserves a full if-else block.
- Good use:String label = (count == 1) ? "item" : "items";, concise, readable, single selection.
- Good use:int max = (a > b) ? a : b;, picking the larger of two values.
- Avoid:Nesting ternary operators inside each other. It saves lines but creates code that is genuinely difficult to reason about.
- Avoid:Using ternary when the true/false branches involve method calls with side effects. The intent becomes unclear.
Ternary Operator
JavaSimple value selection, minimum/maximum, and pluralisation, all practical ternary patterns.
instanceof Operator
The instanceof operator tests whether an object is an instance of a specified type (class, interface, or supertype). It returns a boolean. You use it when you hold a reference of a general type and need to check the actual runtime type before casting. If the reference is null, instanceof returns false rather than throwing a NullPointerException, which makes it safe to use directly.
Pattern matching instanceof (Java 16+)
Java 16 introduced pattern matching for instanceof, which eliminates the redundant cast that previously followed every instanceof check.
- Old style (before Java 16):if (obj instanceof String) { String s = (String) obj; ... }, you check the type and then cast.
- New style (Java 16+):if (obj instanceof String s) { ... }, if the check passes, s is automatically available as a String with no separate cast.
- Pattern matching reduces boilerplate and eliminates the small window where someone could insert code between the check and the cast.
instanceof and Pattern Matching
JavaType checking with instanceof, null safety, and the pattern matching shorthand.
Operator Precedence
When an expression contains multiple operators, Java uses a fixed set of precedence rules to determine which operation is performed first. Operators with higher precedence bind more tightly to their operands than operators with lower precedence. When two operators share the same precedence level, associativity determines the order: most Java operators are left-to-right, but assignment operators are right-to-left.
Precedence table (highest to lowest)
Memorising this table in full is not necessary. What matters is knowing the broad categories and using parentheses whenever there is genuine ambiguity.
- 1. Postfix: x++ x--
- 2. Prefix/Unary: ++x --x +x -x ~ !
- 3. Multiplicative: * / %
- 4. Additive: + -
- 5. Shift: << >> >>>
- 6. Relational: < > <= >= instanceof
- 7. Equality: == !=
- 8. Bitwise AND: &
- 9. Bitwise XOR: ^
- 10. Bitwise OR: |
- 11. Logical AND: &&
- 12. Logical OR: ||
- 13. Ternary: ?:
- 14. Assignment: = += -= *= /= %= &= |= ^= <<= >>=
Practical rules for writing clear expressions
Following these rules avoids bugs caused by misunderstood precedence.
- Use parentheses to make complex expressions unambiguous: (a + b) * c is clearer than a + b * c even though * has higher precedence.
- Never rely on the difference between && and & precedence for correctness. Make the intent explicit.
- Assignment has the lowest precedence of all, which is why if (x = 5) is a bug waiting to happen (assigns 5, then tests 5, which is truthy).
- The ternary operator has very low precedence: a + b > c ? x : y means (a + b > c) ? x : y, not a + (b > c ? x : y).
Precedence in Practice
JavaExpressions that look similar but evaluate differently based on precedence, plus parentheses showing explicit grouping.
Quiz - Test Your Knowledge
Ten questions covering arithmetic, increment/decrement, compound assignment, bitwise, comparison, logical, ternary, instanceof, and precedence. Work through each one carefully before selecting your answer.
Knowledge Check
1. What is the result of 17 % 5 in Java?
2. Given int x = 5; what is the value of x after the expression x++?
3. Which operator performs a logical AND without short-circuit evaluation?
4. What does the unsigned right shift operator >>> do differently from >>?
5. What is the result of the expression (10 > 5) ? "yes" : "no"?
6. What does the compound assignment operator x >>= 2 do?
7. In Java, what does the instanceof operator return?
8. Which operator has the highest precedence in Java?
9. What is the result of 5 & 3 in Java?
10. Which of the following correctly uses the compound assignment operator for addition?