← Back to Chapters

Java Relational Operators

? Java Relational Operators

? Quick Overview

Relational operators in Java are used to compare two values or variables. The result of a relational operation is always a boolean value: true or false.

? Key Concepts

  • Used in decision-making and conditions
  • Mostly used with if, while, and for statements
  • Return only boolean values
  • Cannot be used with objects directly

? Syntax / Theory

Java provides six relational operators:

  • == Equal to
  • != Not equal to
  • > Greater than
  • < Less than
  • >= Greater than or equal to
  • <= Less than or equal to

? Code Example

? View Code Example
// Demonstrating relational operators in Java
class RelationalDemo {
public static void main(String[] args) {
int a = 10;
int b = 20;

System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
}
}

? Output / Explanation

Each comparison checks the relationship between a and b and prints either true or false based on the condition.

✅ Tips & Best Practices

  • Use relational operators inside conditional statements
  • Avoid using == for object comparison
  • Ensure operands are compatible data types

? Try It Yourself

  • Compare two user-input numbers
  • Check if a number is within a given range
  • Use relational operators inside a loop condition