Codectionary / Developer documentation / Java

Comparison & Logical Operators

Comparison operators (==, !=, <, >, <=, >=) compare two values and evaluate to a boolean. Logical operators (&&, ||, !) combine or invert boolean expressions, with && and || short-circuiting - meaning the second operand is skipped entirely if the first already determines the result. Importantly, == compares object references for non-primitive types like String, so .equals() should be used to compare their actual content.

Syntax

==  !=  <  >  <=  >=   &&  ||  !

Examples

Comparison Operators

Comparing primitive values to produce a boolean result.

int a = 5, b = 3;

System.out.println(a == b);  // false
System.out.println(a != b);  // true
System.out.println(a > b);   // true
System.out.println(a <= b);  // false

Logical Operators

Combining boolean expressions with &&, ||, and !.

int age = 25;
boolean hasId = true;

if (age >= 18 && hasId) {
    System.out.println("Entry allowed");
}

boolean isWeekend = false;
boolean isHoliday = true;

if (isWeekend || isHoliday) {
    System.out.println("No work today");
}

boolean isBanned = false;
if (!isBanned) {
    System.out.println("Access granted");
}

Comparing Strings: == vs .equals()

A very common Java pitfall - == compares references, not content, for objects like String.

String a = new String("hello");
String b = new String("hello");

System.out.println(a == b);        // false - different objects in memory
System.out.println(a.equals(b));   // true  - same content

String c = "hello";
String d = "hello";
System.out.println(c == d);        // true - string literals are pooled/interned

Best practices

  • Always use .equals() to compare the content of objects like String - only use == to check if two references point to the exact same object
  • Take advantage of short-circuit evaluation: put cheaper or null-checking conditions first in && expressions to avoid unnecessary work or NullPointerExceptions
  • Wrap multi-condition logical expressions in parentheses for clarity, even when not strictly required by operator precedence
  • Never rely on string literal pooling (== happening to work for literals) - it's an implementation detail, not a guarantee for all String objects

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading