Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 201 ยท Operators

Comparison and Logical Operators

Compare values in Java with ==, !=, <, >, <= and >=, combine conditions with &&, || and !, understand short-circuiting, and see why objects need equals().

Programs make decisions all the time: is the password long enough, is the cart empty, did the user type "quit"? Every one of those questions is a boolean expression, a piece of code that evaluates to true or false. In Java you build them with two groups of operators. Comparison (or relational) operators compare two values, and logical operators combine several conditions into one.

This lesson covers both groups, including two ideas that matter in every real program: short-circuit evaluation, which lets one condition protect another, and the difference between == and equals() when you compare objects.

Comparison operators

Java has six comparison operators. Each takes two operands and produces a boolean:

Operator Meaning Example Result
== equal to 3 == 3 true
!= not equal to 3 != 4 true
< less than 2 < 1 false
> greater than 9 > 4 true
<= less than or equal to 5 <= 5 true
>= greater than or equal to 1 >= 2 false

The result is a value like any other. You can print it, store it in a boolean variable, or use it directly in an if statement:

Java Comparing numbers and characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the parentheses around (stock == 0). Without them, "Out of stock? " + stock == 0 would first join the string and the number and then try to compare a String with 0, which doesn't compile. Whenever you put a comparison inside string concatenation, wrap it in parentheses.

The ordering operators <, >, <= and >= work only on numbers and char. == and != also work on boolean values and on object references, which we'll come back to at the end.

You can't chain comparisons

In math you might write 1 โ‰ค x โ‰ค 10. Java does not allow 1 <= x <= 10: the first part, 1 <= x, produces a boolean, and you can't compare a boolean with 10. The compiler reports bad operand types for binary operator '<='. Spell out both halves and join them with &&:

Java
boolean inRange = x >= 1 && x <= 10;

Comparing floating-point numbers

Comparison with double and float follows the rules from Working with Numbers, and two of them catch people out. First, most decimal fractions can't be stored exactly, so arithmetic that "should" be equal often isn't. Second, NaN (not a number) is not equal to anything, not even itself.

Java Floating-point comparison traps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

For money, avoid double altogether and use BigDecimal (see BigInteger and BigDecimal) or count in whole cents with long. For measurements, compare with a tolerance that makes sense for your data.

Logical operators

Comparisons answer one question. Logical operators combine those answers:

Operator Name true when
&& conditional AND both sides are true
|| conditional OR at least one side is true
! NOT its single operand is false

Here is every combination for two conditions a and b:

a b a && b a || b !a
true true true true false
true false false true false
false true false true true
false false false false true

! binds tightly: !done && ready means (!done) && ready. To negate a whole condition, wrap it in parentheses: !(age >= 13 && age <= 19).

When you combine && and || without parentheses, && is applied first, the same way multiplication comes before addition. So isAdmin || isOwner && isActive means isAdmin || (isOwner && isActive). Even though the rule is well defined, add parentheses whenever you mix the two; the next reader will thank you. Operator Precedence has the full table.

Naming conditions

Long conditions get hard to read quickly. Break them into boolean variables with descriptive names:

Java
boolean hasTicket = tickets > 0;
boolean isWeekend = day.equals("Sat") || day.equals("Sun");
boolean canEnter = hasTicket && (isWeekend || isMember);

De Morgan's laws

Two rules let you push a ! inside parentheses, which often makes a condition clearer:

  • !(a && b) is the same as !a || !b
  • !(a || b) is the same as !a && !b

"Not (sunny and warm)" means "not sunny, or not warm". So !(x >= 1 && x <= 10), "x is not in the range", becomes x < 1 || x > 10.

Short-circuit evaluation

&& and || are called conditional operators because they evaluate the right side only if it is needed:

  • With a && b, if a is false the result must be false, so b is skipped.
  • With a || b, if a is true the result must be true, so b is skipped.

This is called short-circuiting, and it's not just an optimization. It lets the left side act as a guard for the right side:

Java Short-circuit guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows that B and D are never checked. Swap the order in the first if to !name.isEmpty() && name != null and the program crashes with a NullPointerException, because the method call now runs before the guard. Order matters: put the cheap or protective check first.

Put the condition that is cheapest, or most likely to decide the result, on the left. If a database lookup and a simple field check are joined with &&, test the field first so the lookup often doesn't run at all.

&, | and ^ on booleans

The single-character operators & and | also work on boolean operands. They compute the same results as && and ||, but they always evaluate both sides. A third operator, ^ (exclusive OR, "XOR"), is true when exactly one side is true.

Java Logical vs conditional operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In everyday code you almost always want && and ||. The non-short-circuit forms are useful when both sides must run, for example when each side calls a validation method that records an error message and you want all the messages, not just the first. Even then, many teams prefer to run the checks as separate statements so the intent is obvious.

For booleans, a ^ b gives the same answer as a != b, and many developers find != easier to read. On integers, &, | and ^ work bit by bit instead, which is the subject of Bitwise and Shift Operators.

A single & in a guard defeats the guard: name != null & name.length() > 0 still calls name.length() when name is null, and throws. If you meant a guard, use &&.

== vs equals() for objects

For primitives like int, double and char, == compares values. For objects it compares references: it asks "are these two variables pointing at the very same object in memory?", not "do these objects hold the same data?". To compare contents, call the equals() method.

The difference shows up most often with strings:

Java References vs contents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both strings hold java, yet == says false because they are two separate objects. equals() compares the characters and says true. The Integer result looks even stranger: Java caches Integer objects from -128 to 127, so small values happen to share an object and larger ones don't. Code that compares wrappers with == works in testing with small numbers and breaks in production. You'll learn more in Strings and Wrapper Classes and Autoboxing.

The rule of thumb:

  • Primitives: compare with ==.
  • Objects (including String, Integer and your own classes): compare with equals(), or Objects.equals(x, y) when either could be null.
  • Use == on objects only when you really mean "the same object", for example comparing enum constants or checking x == null.

Your own classes need to override equals() for this to work; until they do, equals() behaves like ==. The Object Class shows how, and Records generate a correct equals() for you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why doesn't if (0 < x < 10) compile in Java?

    Java evaluates 0 < x first, giving true or false, and then tries boolean < int, which is not allowed. Write x > 0 && x < 10.
  2. 2. What does this print? String s = null; IO.println(s == null || s.length() > 3);

    s == null is true, so || short-circuits and s.length() never runs. The result is true.
  3. 3. After int n = 0; boolean r = (n > 1) & (++n > 0); what is n?

    Unlike &&, the single & always evaluates both sides, so ++n runs and n becomes 1 even though the left side is false.
  4. 4. Which expression is equivalent to !(a || b)?

    By De Morgan's law, "not (a or b)" means "not a and not b".
  5. 5. String x = "hi"; String y = new String("hi"); Which check returns true?

    new String always creates a new object, so == (same object?) is false. equals() compares the characters, which are the same.

Summary

  • The comparison operators ==, !=, <, >, <= and >= produce a boolean. Mixed numeric types are promoted before comparing, and chains like 1 < x < 10 don't compile.
  • Don't compare double results with ==; use a tolerance, and remember that NaN is never equal to anything.
  • &&, || and ! combine conditions. && binds tighter than ||, but parentheses make mixed conditions clearer.
  • && and || short-circuit: the right side runs only when needed, which lets a left-hand check like s != null guard the right side.
  • &, | and ^ on booleans always evaluate both sides; ^ is exclusive OR.
  • For objects, == compares references. Use equals() (or Objects.equals) to compare contents.

Next: Bitwise and Shift Operators, where &, | and ^ work on the individual bits of integers.