Java Operators: Increment, Relational, Logical, Conditional, Bitwise and Precedence
A complete guide to the remaining Java operators: ++ and -- in prefix and postfix form, comparisons, && || ! and short-circuit evaluation, the ?: conditional operator, bitwise & | ^ ~ and shifts, plus the full operator precedence table.
kvi5hnuCode Sprout team member11 min readOn this page
You've seen the arithmetic operators and conversions. This article covers the rest of Java's operators: increment and decrement, comparisons, logical operators with short-circuit evaluation, the conditional operator, the bitwise operators, and finally the precedence rules that decide what an expression without parentheses means.
Increment and Decrement: ++ and --
Adding or subtracting 1 is so common that Java (like C and C++) has dedicated operators:
int n = 12;
n++; // n is now 13
n--; // back to 12
Because they change a variable, they can only be applied to variables, not to values: 4++ and (a + b)++ are compile errors.
Prefix vs postfix
Each operator has two forms:
- Prefix
++n: increment first, then use the new value. - Postfix
n++: use the old value, then increment.
As stand-alone statements (n++; or ++n;) they do exactly the same thing. The difference only shows when the operator is used inside an expression:
public class Solution {
public static void main(String[] args) {
int m = 7;
int n = 7;
int a = 2 * ++m; // m becomes 8 first, then a = 16
int b = 2 * n++; // b = 14 using the old n, then n becomes 8
System.out.println(a + " " + m + " " + b + " " + n);
int i = 5;
i = i++; // a classic trap
System.out.println(i);
}
}
16 8 14 8
5
The trap on the last lines: i = i++ evaluates i++, which yields the old value 5 and then sets i to 6. Then the assignment stores the yielded 5 back into i, undoing the increment. The result is 5.
Relational (Comparison) Operators
Comparisons produce a boolean:
| Operator | Meaning | Example | Value |
|---|---|---|---|
== | equal to | 3 == 7 | false |
!= | not equal to | 3 != 7 | true |
< | less than | 3 < 7 | true |
> | greater than | 3 > 7 | false |
<= | less than or equal to | 7 <= 7 | true |
>= | greater than or equal to | 3 >= 7 | false |
Points to remember:
- Equality is
==(two equals signs). A single=is assignment. Java's type checking catchesif (x = 0)for numbers (see the char/boolean article), but stay careful. - Don't compare floating-point results with
==(rounding errors); compare with a tolerance. - For objects,
==compares identity (are these the same object?), not content. Strings in particular must be compared withequals, as the strings article explains in detail. - There's no chained comparison:
0 < x < 10doesn't compile in Java. Write0 < x && x < 10.
Logical Operators: &&, ||, !
| Operator | Name | True when |
|---|---|---|
a && b | conditional and | both a and b are true |
a || b | conditional or | at least one of a, b is true |
!a | not | a is false |
Short-circuit evaluation
&& and || evaluate their right operand only if it's needed:
- For
a && b: ifaisfalse, the result must befalse, sobis not evaluated. - For
a || b: ifaistrue, the result must betrue, sobis not evaluated.
This is extremely useful for guarding against errors:

public class Solution {
public static void main(String[] args) {
int x = 0, y = 3;
boolean safe = x != 0 && 10 / x > y; // short-circuit: no division by zero
System.out.println(safe);
System.out.println(x == 0 || 10 / x > y);
int smaller = x < y ? x : y;
System.out.println(smaller);
String sign = y > 0 ? "positive" : y < 0 ? "negative" : "zero";
System.out.println(sign);
}
}
false
true
0
positive
You'll use this pattern constantly with objects: if (name != null && name.length() > 0). If name is null, the call name.length() would throw a NullPointerException, but it never happens because && stops after the first operand.
Order matters: 10 / x > y && x != 0 would crash, because the dangerous part runs first.
The Conditional Operator ?:
The conditional operator (also called the ternary operator, as it has three operands) chooses between two values:
condition ? valueIfTrue : valueIfFalse
int smaller = x < y ? x : y; // the smaller of x and y
String label = count == 1 ? "item" : "items";
Unlike an if statement, ?: is an expression: it produces a value you can assign, return or print. Only the chosen branch is evaluated. You can nest it, as in the sign example above, but beyond one level it gets hard to read; prefer if/else or a switch expression (next article).
Bitwise Operators
Integer values are stored as bit patterns, and Java has operators that work directly on those bits. You need them for flags, masks, low-level protocols, hashing, graphics and some algorithms.
| Operator | Name | Effect on each bit position |
|---|---|---|
a & b | AND | 1 if both bits are 1 |
a | b | OR | 1 if either bit is 1 |
a ^ b | XOR (exclusive or) | 1 if the bits differ |
~a | NOT (complement) | flips every bit |
a << n | left shift | moves bits left by n, filling with 0 (multiplies by 2ⁿ) |
a >> n | signed right shift | moves bits right, filling with copies of the sign bit |
a >>> n | unsigned right shift | moves bits right, filling with 0 |

public class Solution {
public static void main(String[] args) {
int n = 0b1010_1100;
System.out.println(Integer.toBinaryString(n));
System.out.println((n & 0b1000) >> 3); // is bit 3 set?
System.out.println(Integer.toBinaryString(n | 0b1)); // set bit 0
System.out.println(Integer.toBinaryString(n & ~0b100)); // clear bit 2
System.out.println(Integer.toBinaryString(n ^ 0b1111)); // flip low 4 bits
System.out.println(1 << 4); // 16
System.out.println(-16 >> 2); // -4: sign extended
System.out.println(-16 >>> 28); // 15: zeros shifted in
System.out.println(1 << 35); // same as 1 << 3
System.out.println(Integer.bitCount(n) + " " + Integer.highestOneBit(n) + " " + Integer.numberOfTrailingZeros(n));
boolean flag = true & false | true; // non-short-circuit on booleans
System.out.println(flag + " " + (true ^ true));
}
}
10101100
1
10101101
10101000
10100011
16
-4
15
8
4 128 2
true false
Common bit-manipulation idioms
Bits are numbered from 0 at the right. 1 << k is a number with only bit k set, called a mask:
| Task | Code |
|---|---|
Test bit k | (n & (1 << k)) != 0 |
Set bit k | n |= 1 << k |
Clear bit k | n &= ~(1 << k) |
Toggle bit k | n ^= 1 << k |
Extract bit k as 0/1 | (n >> k) & 1 |
| Multiply / divide by 2ᵏ | n << k / n >> k (for non-negative n) |
Is n a power of two? (n > 0) | (n & (n - 1)) == 0 |
Shift details
>>is an arithmetic shift: it preserves the sign, so-16 >> 2is-4.>>>is a logical shift: it fills with zeros, so a negative number becomes a large positive one. There's no<<<, as a left shift fills with zeros anyway.- The shift distance is taken modulo 32 for
int(modulo 64 forlong):1 << 35equals1 << 3= 8. Shifting anintby 32 shifts by 0! - In C and C++, whether
>>on a negative number is arithmetic or logical depends on the compiler. Java defines both precisely.
&, | and ^ with booleans
Applied to boolean values, & and | compute logical and/or, but without short-circuiting: both operands are always evaluated. ^ on booleans is exclusive or (true when exactly one is true). Use && and || for normal conditions; & and | on booleans are for the rare cases where both sides have side effects that must happen.
Operator Precedence and Associativity
When an expression has several operators and no parentheses, precedence decides which operator binds first, and associativity decides the order among operators of equal precedence. The table lists Java's operators from highest to lowest precedence:
| Level | Operators | Associativity |
|---|---|---|
| 1 | [] (array index), . (member access), () (method call), postfix x++ x-- | left to right |
| 2 | prefix ++x --x, unary + -, !, ~, (type) cast, new | right to left |
| 3 | * / % | left to right |
| 4 | + - (also string concatenation) | left to right |
| 5 | << >> >>> | left to right |
| 6 | < <= > >= instanceof | left to right |
| 7 | == != | left to right |
| 8 | & | left to right |
| 9 | ^ | left to right |
| 10 | | | left to right |
| 11 | && | left to right |
| 12 | || | left to right |
| 13 | ?: | right to left |
| 14 | = += -= *= /= %= &= |= ^= <<= >>= >>>=, and -> (lambda) | right to left |
Examples:
a && b || cmeans(a && b) || c, because&&binds tighter than||.2 + 3 * 4is14;(2 + 3) * 4is20.a += b += cmeansa += (b += c)(right to left).x > 0 & y > 0works because comparisons bind tighter than&. Butflags & MASK == 0meansflags & (MASK == 0), which doesn't compile for ints. Write(flags & MASK) == 0.-x * yis(-x) * y: unary minus binds tighter than multiplication.
Common questions
Is i++ faster than i = i + 1 or i += 1?
No. For a local int, i++ and i += 1 compile to the same iinc instruction; i = i + 1 compiles to a load, an add and a store, but the JIT turns all three into the same machine code. Choose the form that reads best. i++ is idiomatic in loops.
Why does -16 >>> 28 give 15?
>>> shifts in zeros from the left, so the sign bits of the negative number become ordinary value bits. -16 is 1111…0000 in binary. Shifting right by 28 leaves the top four 1 bits at the bottom, 1111, which is 15. With >> the result stays -1, because the sign bit is copied.
When should I use ^ on booleans?
When you need "exactly one of the two is true". An example is if (hasCoupon ^ isMember), where giving both discounts would be wrong. For booleans, a ^ b is the same as a != b, and many programmers find != clearer.
Does && always evaluate left to right?
Yes. Java guarantees left-to-right evaluation of operands, and &&/|| skip the right side when the result is already known. That is why obj != null && obj.isValid() is safe. Java also evaluates method arguments left to right, unlike C, where the order is unspecified.
Is x = y = 0 a good idea?
It is a common idiom for resetting several variables of the same type, and it is well defined: assignment is right-associative and yields the assigned value. Avoid more elaborate uses of assignments inside expressions, because they hurt readability.
Summary
++/--add/subtract 1. Prefix uses the new value, postfix the old one; avoid them inside larger expressions (i = i++leavesiunchanged).== != < > <= >=compare numbers and produceboolean. For objects,==checks identity; useequalsfor content.&&,||,!are the logical operators.&&and||short-circuit, which lets you guard risky operations (x != 0 && 10 / x > y,s != null && s.isEmpty()).cond ? a : bis an expression that picks one of two values.- Bitwise
& | ^ ~and shifts<< >> >>>work on integer bits; shift distances are taken mod 32/64.Integer/Longprovide bit helpers. - Precedence: unary > multiplicative > additive > shifts > relational > equality >
&>^>|>&&>||>?:> assignment. Use parentheses for clarity.
Practice Questions
int a = 5; int b = a++ + ++a; What are a and b?
Left to right: a++ yields 5 and sets a to 6; then ++a sets a to 7 and yields 7. So b = 5 + 7 = 12 and a = 7. (This is exactly the kind of code to avoid.)
Why is s != null && s.length() > 3 safe, but s.length() > 3 && s != null is not?
&& evaluates left to right and stops early. In the first version, if s is null the first operand is false and s.length() is never called. In the second, s.length() runs first and throws a NullPointerException when s is null.
Write a single expression that gives "even" or "odd" for an int n.
n % 2 == 0 ? "even" : "odd". This works for negative numbers too, because -3 % 2 is -1, which isn't 0.
What do 13 & 6, 13 | 6, 13 ^ 6 and ~13 evaluate to?
13 = 1101, 6 = 0110. AND = 0100 = 4; OR = 1111 = 15; XOR = 1011 = 11; ~13 = −14 (in two's complement, ~x = −x − 1).
What is the difference between -8 >> 1 and -8 >>> 1?
-8 >> 1 is -4: an arithmetic shift copies the sign bit. -8 >>> 1 fills the top bit with 0, giving a large positive number: 2147483644.
How is a || b && c grouped? And x + y * z > w == flag?
a || (b && c), since && has higher precedence than ||. ((x + (y * z)) > w) == flag: multiplication, then addition, then the relational >, then equality ==.
Previous: Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment
Next: Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
Related reading
- Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment
- Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
- Java Variables, Constants, var and final Explained
- Java Keywords Reference: Every Keyword, Contextual Keyword and Literal
- Java Module Services, requires transitive and static, and Module Tools

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.