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.