Introduction to Java · Introduction to Java Programming

Relational Operators

Watch lectures

Relational Operators

1. What They Do (beginner)

Compare two values → answer is always boolean (true/false). Used in if, while, for to decide. Six: == != > < >= <=.

2. Table + Beginner Code

int marks = 75;
System.out.println(marks > 40);   // true (pass?)
System.out.println(marks == 75);  // true
System.out.println(marks != 75);  // false
System.out.println('b' > 'a');    // true (98 > 97 — chars compare by number!)
Op Meaning Example
== equal? 5==5 → true
!= not equal? 5!=3 → true
> < bigger/smaller? 7>3 → true
>= <= at least / at most? marks>=40 → pass

3. The Two Deadly Traps

// TRAP 1: = vs == (assignment vs comparison)
int x = 5;
// if (x = 5) // ERROR in Java (needs boolean!) — Java saves you, C doesn't
if (x == 5) System.out.println("equal"); // correct

// TRAP 2: String with == ( almighty exam trap!)
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b);      // false! (compares addresses)
System.out.println(a.equals(b)); // true (compares content — CORRECT)

Rule: primitives (int, char) use ==; objects (String) use .equals().

4. Exam Points

  • Predict output + = vs == — 5 marks, very frequent.
  • String == vs .equals() — 5 marks, all-time favourite trap.
Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

← All Introduction to Java Programming modules