Java Programming, Operators · December 2, 2026

Java for Beginners, Lesson 13: Relational and Logical Operators in Java

Java for Beginners · Module 3: Operators


🎯 Asking Questions in Code

Programs need to make decisions: is the student’s mark above 40? Is the user’s age between 18 and 25? Relational operators compare two values, and logical operators combine the answers. Both give a boolean result, true or false, which later drives if statements and loops.

📌 Relational operators: == != < > <= >=. Logical operators: && (AND), || (OR), ! (NOT).

1️⃣ Relational Operators

OperatorMeaningExample (a = 12, b = 20)Result
==equal toa == bfalse
!=not equal toa != btrue
<less thana < btrue
>greater thana > bfalse
<=less than or equala <= 12true
>=greater than or equalb >= 25false
Every relational operator gives a boolean: true or false.

Figure 1: Relational operators compare two values.

Program 1: Comparing values

public class RelDemo {
    public static void main(String[] args) {
        int a = 12, b = 20;
        System.out.println("a == b : " + (a == b));
        System.out.println("a != b : " + (a != b));
        System.out.println("a <  b : " + (a < b));
        System.out.println("a >  b : " + (a > b));
        System.out.println("a <= 12: " + (a <= 12));
        System.out.println("b >= 25: " + (b >= 25));
        System.out.println("'a' < 'b': " + ('a' < 'b'));
        System.out.println("0.1+0.2 == 0.3 : " + (0.1 + 0.2 == 0.3));
        System.out.println("close enough   : " + (Math.abs(0.1 + 0.2 - 0.3) < 1e-9));
    }
}
🖥️ Output:
a == b : false
a != b : true
a < b : true
a > b : false
a <= 12: true
b >= 25: false
‘a’ < ‘b’: true
0.1+0.2 == 0.3 : false
close enough : true
  • == tests equality. A single = is assignment, which is a very different thing.
  • Characters compare by their codes, so 'a' < 'b' is true.
  • Do not compare decimals with ==. Because 0.1 + 0.2 is stored as 0.30000000000000004 (Lesson 8), the test is false. Instead check that the difference is very small, as the last line does with Math.abs.

2️⃣ Logical Operators

ABA && B (AND)A || B (OR)!A (NOT)
truetruetruetruefalse
truefalsefalsetruefalse
falsetruefalsetruetrue
falsefalsefalsefalsetrue
AND needs both true. OR needs at least one true. NOT flips the value.

Figure 2: Truth table for the logical operators.

Program 2: Combining conditions

public class LogicDemo {
    public static void main(String[] args) {
        int marks = 72;
        int attendance = 80;

        boolean passed = marks >= 40;
        boolean eligible = attendance >= 75;
        System.out.println("passed && eligible : " + (passed && eligible));
        System.out.println("passed || eligible : " + (passed || eligible));
        System.out.println("!passed            : " + (!passed));

        boolean distinction = marks >= 75 && attendance >= 75;
        System.out.println("distinction        : " + distinction);

        int age = 19;
        boolean student = age >= 18 && age <= 25;
        System.out.println("age in 18..25      : " + student);
    }
}
🖥️ Output:
passed && eligible : true
passed || eligible : true
!passed : false
distinction : false
age in 18..25 : true
  • You can store the result of a comparison in a boolean variable and reuse it.
  • distinction is false because the marks (72) fail the first test, even though attendance passes.
  • To check a range, write both comparisons and join them with &&: age >= 18 && age <= 25.

3️⃣ Short-Circuit Evaluation

A && B
A is false?
B is skipped
result is already false
A || B
A is true?
B is skipped
result is already true

Figure 3: Short-circuit evaluation: Java stops as soon as the answer is certain.

With && and ||, Java stops evaluating as soon as the answer is certain. The single-character versions & and | always evaluate both sides.

public class ShortCircuit {
    static boolean check(String name, boolean value) {
        System.out.println("  checking " + name);
        return value;
    }

    public static void main(String[] args) {
        System.out.println("Using && :");
        boolean r1 = check("A", false) && check("B", true);
        System.out.println("  result = " + r1);

        System.out.println("Using & :");
        boolean r2 = check("A", false) & check("B", true);
        System.out.println("  result = " + r2);

        System.out.println("Using || :");
        boolean r3 = check("A", true) || check("B", false);
        System.out.println("  result = " + r3);

        int x = 0;
        if (x != 0 && 10 / x > 1) {
            System.out.println("big");
        } else {
            System.out.println("safe: division skipped");
        }
    }
}
🖥️ Output:
Using && :
checking A
result = false
Using & :
checking A
checking B
result = false
Using || :
checking A
result = true
safe: division skipped
  • With &&, A is false, so B is never checked. With &, both are checked.
  • With ||, A is true, so B is skipped.
  • The last block shows why short-circuiting is useful: since x != 0 is false, 10 / x never runs, so there is no divide-by-zero error.
  • The check method here is a small helper that prints a message and returns the value. Methods are covered in Lesson 25.

4️⃣ == Compares References for Objects

For primitives, == compares values. For objects such as String, == asks whether both names point to the same object. To compare the contents, use equals().

public class EqualsTrap {
    public static void main(String[] args) {
        String s1 = new String("java");
        String s2 = new String("java");
        System.out.println("s1 == s2      : " + (s1 == s2));
        System.out.println("s1.equals(s2) : " + s1.equals(s2));
    }
}
🖥️ Output:
s1 == s2 : false
s1.equals(s2) : true
  • Two separate objects hold the same text, so == is false and equals() is true. Lesson 23 explains this fully.

5️⃣ Errors Beginners Meet

Assignment instead of comparison

public class Bad1 {
    public static void main(String[] args) {
        int a = 5;
        if (a = 5) {
            System.out.println("five");
        }
    }
}
🖥️ Compiler message:
Bad1.java:4: error: incompatible types: int cannot be converted to boolean
if (a = 5) {
^
1 error
  • a = 5 assigns and produces an int, not a boolean. Write a == 5. (In Java this mistake is caught by the compiler. In C it would compile silently.)

Chaining comparisons like in maths

public class Bad2 {
    public static void main(String[] args) {
        int x = 15;
        boolean ok = 10 < x < 20;
        System.out.println(ok);
    }
}
🖥️ Compiler message:
Bad2.java:4: error: bad operand types for binary operator ‘<‘
boolean ok = 10 < x < 20;
^
first type: boolean
second type: int
1 error
  • 10 < x becomes a boolean, which cannot be compared to 20. Write 10 < x && x < 20.

⚠️ Common Mistakes

MistakeProblemFix
Using = to compareAssignment, not comparisonUse ==
10 < x < 20Not allowed in Java10 < x && x < 20
Comparing Strings with ==Compares referencesUse equals()
Comparing doubles with ==Tiny rounding errorsCompare with a tolerance
Using & when you meant &&No short-circuitUse && for conditions
Writing =< or =>Wrong orderWrite <= and >=

❓ Frequently Asked Questions

Q1. What is the difference between = and ==?
= stores a value in a variable. == checks whether two values are equal.

Q2. Can I compare a boolean with ==?
Yes, but it is simpler to write if (done) than if (done == true).

Q3. Which has higher priority, && or ||?
&& binds tighter than ||. When in doubt, add brackets. Lesson 15 gives the full order.

Q4. Why is short-circuiting useful?
It avoids errors (like dividing by zero) and saves time by skipping unnecessary checks.

✅ Key Takeaways

  • Relational operators (== != < > <= >=) always give true or false.
  • Logical operators combine conditions: && (both), || (either), ! (flip).
  • && and || short-circuit: the second part is skipped when the answer is already known.
  • Use equals() for Strings and a tolerance for decimals.
  • Check a range with two comparisons: x >= 10 && x <= 20.
🎓 Practice questions: (1) Write a boolean expression that is true if a year is a leap year. (2) What does !(5 > 3 && 2 > 4) give? (3) Why does 0.1 + 0.2 == 0.3 give false? (4) Explain how short-circuiting prevents a crash in x != 0 && 10 / x > 1. (5) Write a condition that checks whether a character is an uppercase letter.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision