Operators

Java Program to Demonstrate Relational Operators

A Java program to demonstrate the usage of relational operators.

Problem Description

Write a Java program to compare two numbers using relational operators.

Code

RelationalOperators.java
public class RelationalOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        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: false
a < b: true
a >= b: false
a <= b: true

Explanation

  1. == (Equal to): Checks if values are equal.
  2. != (Not equal to): Checks if values are not equal.
  3. > (Greater than): Checks if the left operand is greater than the right.
  4. < (Less than): Checks if the left operand is less than the right.
  5. >= (Greater than or equal to): Checks if the left operand is greater than or equal to the right.
  6. <= (Less than or equal to): Checks if the left operand is less than or equal to the right.

Try Yourself

  1. Compare Characters: Compare 'a' and 'b'. Is 'a' < 'b' true? Why?
  2. Floating Point: Compare 10.0 and 10. Are they equal?
  3. Negative Numbers: Is -5 > -10 true or false?
  4. Equality Check: Be careful with == vs =. Try if (a = 10) and see the error.
  5. Brain Twister: Why is 0.1 + 0.2 == 0.3 false in Java? (Hint: Floating point precision).