Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Object <= relational operator check

Tags:

java

In Java, when two objects are compared using ==, their references are also compared. But what happens when they are compared using other relational operators? For instance:

 Integer a = new Integer(10);
 Integer b = new Integer(9);
 if (a >= b) {
  System.out.println("A is greater");
 }

When I run this, I get output as A is greater, why so? Do references not get compared or they do and it's just a coincidence?

Also, if one of the arguments is primitive, does the non-primitive one get unwrapped to primitive for such comparisons?

like image 976
Arnav Sengupta Avatar asked Mar 15 '26 17:03

Arnav Sengupta


1 Answers

In your example, the Integer(s) are unboxed to primitive int(s). There is no <= (or >=) comparison for reference types (without Comparable, Comparator or similar).

like image 171
Elliott Frisch Avatar answered Mar 18 '26 06:03

Elliott Frisch