Java Equality, Relational, Logical and Ternary Operators (OCP 21)
The comparison and decision operators for the OCP Java 21 exam: == and != on primitives and references, relational operators, instanceof and its compile-time checks, & | ^ as logical and bitwise operators, short-circuit && and ||, and the ternary operator's evaluation and result types.
kvi5hnuCode Sprout team member9 min readOn this page
The last group of operators produces boolean results, or chooses between values. These operators drive every if, loop and stream filter, and they're full of exam traps: comparing references instead of values, right-hand sides that never run, and ternaries whose type isn't what it looks like. This article covers all of them.
Equality operators: == and !=
| Operands | a == b is true when |
|---|---|
Two numbers (any numeric types, including char) | the values are equal after numeric promotion |
Two boolean values | both are true or both are false |
| Two references | both point to the same object, or both are null |
System.out.println(5 == 5.0); // true: 5 is promoted to 5.0
System.out.println('A' == 65); // true: char is numeric
System.out.println(null == null); // true
You can't mix kinds. A number can't be compared with a boolean, and a primitive can't be compared with an unrelated reference type:
boolean m = true == 3; // DOES NOT COMPILE
boolean a = false != "Pear"; // DOES NOT COMPILE
boolean g = 4.5 == "Max"; // DOES NOT COMPILE
The same rule applies to two references whose types can never refer to the same object, such as a String and a StringBuilder, or an Integer and a Long. Those comparisons don't compile.
References compare identity
For objects, == asks "same object?", not "same contents?":
String a = new String("kiwi");
String b = new String("kiwi");
String c = b;
System.out.println(a == b); // false: two different objects
System.out.println(b == c); // true: one object, two references
System.out.println(a.equals(b)); // true: equals compares contents
new always creates a new object, so two new expressions never give == references. Use equals to compare contents. The core APIs chapter covers the string pool, where "kiwi" == "kiwi" is true, and the wrapper cache.
Floating-point equality has its own surprises: 0.1 + 0.2 == 0.3 is false because of binary rounding, and Double.NaN == Double.NaN is false.
Don't confuse = with ==
boolean bear = false;
boolean polar = (bear = true); // assignment: polar is true
This compiles only because the variables are boolean. Article 9 explains how the value of an assignment is used.
Relational operators
<, <=, > and >= work only on numeric operands (promoted as usual) and return a boolean:
int gibbon = 2, wolf = 4, ostrich = 2;
System.out.println(gibbon < wolf); // true
System.out.println(gibbon >= ostrich); // true
System.out.println(gibbon > ostrich); // false: equal is not greater
They can't be chained: 1 < x < 10 doesn't compile, because 1 < x is a boolean, and a boolean can't be compared with <. Write 1 < x && x < 10.
instanceof
obj instanceof Type is true when the object that obj refers to is an instance of Type or one of its subtypes. It checks the runtime object, not the declared type of the variable:
Integer busNo = Integer.valueOf(9);
Number num = busNo;
Object obj = busNo; // one object, three references
num instanceof Integer // true
obj instanceof Number // true
obj instanceof Comparable // true: Integer implements Comparable
A common use is to check before casting:
public void showBus(Number time) {
if (time instanceof Integer) {
System.out.print("bus " + (Integer) time);
} else {
System.out.print(time);
}
}
The next chapter introduces pattern matching (time instanceof Integer bus), which tests, casts and declares a variable in one step. It's the modern way to write this.
Three rules to know:
null instanceof AnyTypeisfalse. Anullreference is never an instance of anything.null instanceof nulldoesn't compile, because the right side must be a type.- Impossible checks don't compile. If the compiler can prove that the variable's type and the tested type have no object in common, it reports an error.
Number n; n instanceof Stringfails, becauseNumberandStringare unrelated classes. Testing a non-finalclass against an interface compiles (n instanceof Runnable), because some subclass ofNumbercould implementRunnable. Testing afinalclass that doesn't implement the interface fails (String s; s instanceof Runnable). - The left side must be a reference.
int x; x instanceof Integerdoesn't compile in Java 21. Primitive types ininstanceofare a preview feature in later releases, not part of either exam.
Logical and bitwise operators: &, |, ^
These three operators have two meanings:
- With
booleanoperands they're logical operators, and they always evaluate both sides. - With integer operands they're bitwise operators, combining the numbers bit by bit.

Memory aids:
- AND is
trueonly if both sides aretrue. - Inclusive OR is
falseonly if both sides arefalse. - Exclusive OR (XOR) is
trueonly if the sides differ.
boolean doorLocked = true, lightsOff = true;
doorLocked | lightsOff // true
doorLocked & lightsOff // true
doorLocked ^ lightsOff // false: they're the same
On integers the same rules apply to each pair of bits:
6 & 3 // 0b110 & 0b011 = 0b010 = 2
6 | 3 // 0b110 | 0b011 = 0b111 = 7
6 ^ 3 // 0b110 ^ 0b011 = 0b101 = 5
Some patterns are worth remembering: n & n and n | n give n, and n ^ n gives 0. For a number and its complement, n & ~n is 0 and n | ~n and n ^ ~n are both -1.
You can't mix kinds: 5 & true doesn't compile.
Conditional (short-circuit) operators: && and ||
&& and || give the same results as & and | on booleans, but they stop as soon as the answer is known:
left && right: ifleftisfalse, the result isfalseandrightis not evaluated.left || right: ifleftistrue, the result istrueandrightis not evaluated.
They work only on boolean operands, and their precedence is lower than &, ^ and |: && binds tighter than ||.
The everyday use is guarding against null:
if (duck != null && duck.age() < 5) { ... } // safe: age() isn't called on null
if (duck != null & duck.age() < 5) { ... } // NullPointerException when duck is null
Unperformed side effects
The exam often puts an increment or a method call on the right side of && or || and then asks for a variable's value:
int tokens = 8;
boolean allowed = (tokens >= 8) || (++tokens <= 9);
System.out.println(tokens); // 8: the left side was true, so ++tokens never ran
With | instead of ||, both sides run and tokens becomes 9. When you see && or ||, first evaluate the left side, decide whether the right side runs at all, and only then think about side effects.
The ternary operator ? :
The conditional operator, usually called the ternary operator, picks one of two values:
booleanExpression ? valueIfTrue : valueIfFalse
int owl = 5;
int food = owl < 2 ? 3 : 4; // 4
That's the same as an if/else that assigns food, written as an expression. The rules:
-
The first operand must be a
boolean. -
Only one of the other two operands is evaluated. Side effects in the branch that isn't taken never happen:
javaint x = 1, y = 1; int picked = x > 0 ? x++ : y++; // picked = 1, x = 2, y unchanged -
It groups right to left, so nested ternaries read from the right:
a ? b : c ? d : emeansa ? b : (c ? d : e). Parentheses make nested ternaries much easier to read:javaint f1 = owl < 4 ? owl > 2 ? 3 : 4 : 5; int f2 = owl < 4 ? (owl > 2 ? 3 : 4) : 5; // same thing, readable -
A ternary is an expression, not a statement.
x > 2 ? x++ : x--;on its own line doesn't compile.
The type of a ternary
The two branches don't need the same type, but the result must fit wherever it's used:
int score = 7;
System.out.println(score > 5 ? 21 : "Low"); // OK: println(Object) takes either
int level = score < 9 ? 3 : "High"; // DOES NOT COMPILE: "High" isn't an int
When both branches are numeric, the result type follows rules much like promotion. Watch these cases:
| Expression | Result |
|---|---|
true ? 1 : 2.0 | 1.0: int and double give a double |
true ? 'A' : 0 | 'A': a char and an int constant that fits in a char give a char |
true ? 'A' : zero (where int zero = 0) | 65: a char and an int variable give an int |
true ? nullInteger : 0 | NullPointerException: the Integer is unboxed to int |
The last row is a classic runtime trap. When one branch is an Integer and the other is an int, the result type is int, so a null Integer is unboxed and throws.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- The ternary operator and
switchexpressions (article 12) can both pick a value. Modern code often uses aswitchexpression where older code nested ternaries.
Exam traps from this article
A complete example
public class Solution {
record Duck(String name, int age) { }
static int calls = 0;
static boolean check(String label, boolean result) {
calls++;
System.out.print(label + " ");
return result;
}
static String describe(Number n) {
// instanceof tests the object's runtime type; a cast then gives access to it as that type.
if (n instanceof Integer) {
return "bus " + (Integer) n;
}
return n + " (not a bus number)";
}
public static void main(String[] args) {
// 1. == on primitives compares values (after promotion); on references, identity.
String a = new String("kiwi");
String b = new String("kiwi");
String c = b;
System.out.println((5 == 5.0) + " " + ('A' == 65) + " " + (a == b) + " " + (b == c) + " " + a.equals(b));
// 2. Relational operators and instanceof.
Object time = Integer.valueOf(9);
System.out.println((3 <= 3) + " " + (time instanceof Number) + " " + (null instanceof Object));
System.out.println(describe(9) + " | " + describe(9.5));
// 3. & | ^ on booleans always evaluate both sides; && and || may skip the right side.
calls = 0;
boolean both = check("L", false) & check("R", true);
System.out.println("& -> " + both + ", calls=" + calls);
calls = 0;
boolean shortCircuit = check("L", false) && check("R", true);
System.out.println("&& -> " + shortCircuit + ", calls=" + calls);
System.out.println("true ^ true = " + (true ^ true) + ", true ^ false = " + (true ^ false));
// 4. Short-circuiting guards against null.
Duck duck = null;
if (duck != null && duck.age() < 5) {
System.out.println("young duck");
} else {
System.out.println("no young duck (and no NullPointerException)");
}
// 5. Unperformed side effects.
int tokens = 8;
boolean allowed = (tokens >= 8) || (++tokens <= 9);
System.out.println("tokens=" + tokens + ", allowed=" + allowed);
// 6. The ternary operator evaluates only the chosen branch.
int owl = 3;
int food = owl < 4 ? (owl > 2 ? 3 : 4) : 5;
int x = 1, y = 1;
int picked = x > 0 ? x++ : y++;
System.out.println("food=" + food + ", picked=" + picked + ", x=" + x + ", y=" + y);
// 7. Ternary result types: different types are allowed, but they must fit the target.
int score = 7;
System.out.println(score > 5 ? 21 : "Low"); // println(Object) accepts either
System.out.println(true ? 1 : 2.0); // numeric operands are promoted: 1.0
int zero = 0;
System.out.println(true ? 'A' : zero); // char and int variable: int 65
System.out.println(true ? 'A' : 0); // char and a constant that fits: char A
// 8. Bitwise operators on integers.
System.out.println((6 & 3) + " " + (6 | 3) + " " + (6 ^ 3));
}
}
Output:
true true false true true
true true false
bus 9 | 9.5 (not a bus number)
L R & -> false, calls=2
L && -> false, calls=1
true ^ true = false, true ^ false = true
no young duck (and no NullPointerException)
tokens=8, allowed=true
food=3, picked=1, x=2, y=1
21
1.0
65
A
2 7 5
Points to notice:
- With
&, bothLandRprint andcallsis 2. With&&, thefalseleft side stops the evaluation, soRnever prints. describe(9)passes anintthat is autoboxed to anInteger, so theinstanceoftest istrue.9.5becomes aDouble.- The last three ternaries print the same character, or not:
65versusAdepends only on whether the other operand is a constant.
Common questions
When should I use & instead of && on booleans?
Almost never in real code. Use & only when the right side must run for its side effect, and even then, separate statements are clearer. On the exam, & and | appear mostly to test whether you notice that both sides run.
Does instanceof work with interfaces?
Yes. obj instanceof Comparable is true if the object's class implements Comparable, directly or through a superclass.
Why does score > 5 ? 21 : "Low" compile in println but not in an int assignment?
The ternary's type is then a common supertype of Integer and String (effectively Object). println(Object) accepts it, but an int variable can't.
Is the ternary operator faster than if/else?
No. The difference is purely about style. Use a ternary for a simple choice between two values, and if/else (or a switch expression, next chapter) for anything more complex.
Do && and || have the same precedence?
No. && binds tighter, so a || b && c means a || (b && c). Use parentheses when you mix them.
Summary
==and!=compare values for primitives (after promotion) and identity for references. Mixing numbers with booleans, or unrelated reference types, doesn't compile.<,<=,>and>=work on numbers only.instanceofchecks the runtime object, returnsfalsefornull, and doesn't compile when the check is impossible.&,|and^are logical operators on booleans, always evaluating both sides, and bitwise operators on integers.&&and||skip the right side when the left side decides the result. Side effects on the right may never happen.? :evaluates only the chosen branch. Its result type must fit the target, numeric branches are promoted, and anInteger/intmix can throw aNullPointerException.
Practice quiz
Test yourself with the equality, logical and ternary operators quiz: 10 exam-style questions with explanations. Then take the Chapter 2 review: 20 mixed questions on all operators.
Previous: Java Arithmetic, Numeric Promotion, Casting and Assignment Operators (OCP 21)
Next: Java if/else, Pattern Matching for instanceof and Flow Scoping (OCP 21)
Related reading
- Java Arithmetic, Numeric Promotion, Casting and Assignment Operators (OCP 21)
- Java Operators: Types, Precedence and Unary Operators (OCP 21)
- Java Variable Scope and Garbage Collection (OCP 21)
- Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.