Java - AutoBoxing/Unboxing and Comparison Operators

Introduction

If a numeric wrapper object is used with these comparison operators, it must be unboxed and the corresponding primitive type.

Consider the following snippet of code:

Integer a = 100;
Integer b = 100;
System.out.println("a : " + a);
System.out.println("b : " + 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));

If you mix the two types, reference and primitive, with these comparison operators, you still get the same results.

The reference type is unboxed and a comparison with the two primitive types takes place. For example,

if (101 > new Integer(100)) {

}

is converted to

if(101 <= (new Integer(100)).intValue()) {
}

Demo

public class Main {
  public static void main(String[] args) {
    Integer a = 100;//from www.  j ava2s .  c  om
    Integer b = 100;
    System.out.println("a : " + a);
    System.out.println("b : " + 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));
  }

}

Result

Related Topic