Java Tutorial Java Advanced Java References

Java - comparison operators example



The example below illustrates the usage of Java comparison operators: ==, !=, >, <, >=, <=.

public class MyClass {
  public static void main(String[] args) {
    System.out.println("10 == 10: "+ (10 == 10));
    System.out.println("10 != 10: "+ (10 != 10));
    System.out.println("10 < 20: "+ (10 < 20));
    System.out.println("10 > 20: "+ (10 > 20));
    System.out.println("10 <= 20: "+ (10 <= 20));
    System.out.println("10 >= 20: "+ (10 >= 20));
  }
}

The output of the above code will be:

10 == 10: true
10 != 10: false
10 < 20: true
10 > 20: false
10 <= 20: true
10 >= 20: false

These comparison operators generally return boolean results, which is very useful and can be used to construct conditional statement as shown in the example below:

public class MyClass {
  static void range_func(int x){
    //&& operator is used to combine conditions
    //returns true only when x >= 10 and x <= 25
    if(x >= 10 && x <= 25)
      System.out.println(x +" belongs to range [10, 25]."); 
    else
      System.out.println(x +" do not belongs to range [10, 25].");
  }

  public static void main(String[] args) {
    range_func(15);
    range_func(25);
    range_func(50);
  }
}

The output of the above code will be:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].

❮ Java - Operators