Relational (Comparison) Operators in Java
Relational operators are used to compare two values.
The result of these comparisons is always a boolean value: true or false. These operators are commonly used in conditions, like in if, while, and loops.
List of Relational Operators
| Operator | Name | Meaning | Example | Result |
|---|---|---|---|---|
| == | Equal to | Returns true if both values are equal | 5 == 5 | true |
| != | Not equal to | Returns true if values are not equal | 5 != 3 | true |
| > | Greater than | Checks if left is greater than right | 10 > 3 | true |
| < | Less than | Checks if left is less than right | 2 < 5 | true |
| >= | Greater than or equal to | Checks if left is ≥ right | 5 >= 5 | true |
| <= | Less than or equal to | Checks if left is ≤ right | 3 <= 6 | true |
Notes:
- These operators help your program decide something (true/false).
- Mostly used in if, while, for conditions.
- Always returns a boolean value (true or false).
- You can also use these with characters and floating-point numbers (like a < b or 3.5 > 2.2).
Example: Relational Operators in Action
class ShikshaSanchar {
public static void main(String[] args) {
int a = 10, b = 5;
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 >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
}
}
Output:
a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false
Explanation:
- a == b → 10 == 5 → false
- a != b → 10 != 5 → true
- a > b → 10 > 5 → true
- a < b → 10 < 5 → false
- a >= b → 10 >= 5 → true
- a <= b → 10 <= 5 → false
Example: Using Relational Operator in an if Condition
class ShikshaSanchar {
public static void main(String[] args) {
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
}
}
Output:
You are eligible to vote.
Explanation:
- This uses the >= operator to check if the user is 18 or older.
- If the condition is true, it prints the eligible message.
- Otherwise, it prints the not eligible message.
- A common use case in real applications.
Example: Using Relational Operator in a for Loop
class ShikshaSanchar {
public static void main(String[] args) {
// Print numbers less than 5
for (int i = 1; i < 5; i++) {
System.out.println("i = " + i);
}
}
}
Output:
i = 1
i = 2
i = 3
i = 4
Explanation:
- The for loop runs while the condition i < 5 is true.
- It starts from 1 and goes up to 4.
- i < 5 is the relational condition that controls how long the loop runs.
Summary:
- Used to compare two values and return true or false.
- Commonly used in if, while, and for conditions.
Use == for primitive types,
Use .equals() for objects (e.g., Strings)