Relational Operators

Learn how to compare values in Java using relational operators. These operators evaluate the relationship between two operands and return a boolean result (true or false).

Java · beginner · 15 min · 9 steps · free

What you'll learn

ComparisonDemo.java

public class ComparisonDemo {
    public static void main(String[] args) {
        int a = 15;
        int b = 25;
        
        System.out.println("a = 15, b = 25");
        
        // Equal to operator
        System.out.println("Is a == b? " + (a == b));
        
        // Not equal to operator
        System.out.println("Is a != b? " + (a != b));
        
        // Less than operator
        System.out.println("Is a < b? " + (a < b));
        
        // Greater than operator
        System.out.println("Is a > b? " + (a > b));
        
        // Less than or equal to operator
        System.out.println("Is a <= b? " + (a <= b));
        
        // Greater than or equal to operator
        System.out.println("Is a >= b? " + (a >= b));
    }
}

Step by step

  1. We declare and initialize an integer variable a with the value 15.
  2. Next, we declare and initialize another integer variable b with the value 25.
  3. This line simply prints the initial values of our variables to the console for clarity.
  4. The == operator checks for equality. The expression (a == b) evaluates to 15 == 25, which is false.
  5. The != operator checks for inequality. The expression (a != b) evaluates to 15 != 25, which is true.
  6. The < operator checks if the left operand is less than the right. The expression (a < b) evaluates to 15 < 25, which is true.
  7. The > operator checks if the left operand is greater than the right. The expression (a > b) evaluates to 15 > 25, which is false.
  8. The <= operator checks if the left operand is less than or equal to the right. The expression (a <= b) evaluates to 15 <= 25, which is true.
  9. Finally, the >= operator checks if the left operand is greater than or equal to the right. The expression (a >= b) evaluates to 15 >= 25, which is false.

Common mistakes

Best practices

·

More in Operators