do <= and >= relational operators work with Integer objects

java

Solution

Yes, but note that `Integer` are objects, not primitive `int`. Usage of `>`, `<`, `>=` and `<=` operators are not meant for objects, but for primitives, so when using any of these, the `Integer` is autoboxed to `int`. While when using `==` in objects you are comparing their references. Use `equals` instead to compare them.

Still, note that `Integer` class has an cache that store `Integer` references from `-128` to `127`. This means that if you do this:

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2);

Will print `true`.

Problem

I understand that you can't use == or != to compare values of numeric objects and have to use .equals() instead. But after a fair amount of searching I haven't been able to find a statement about whether or not you can use the other comparison operators, other than suggestions to use .compare() or .compareTo() which feel inefficient because they require two comparisons: a to b, then the result of that to zero. Despite == and != comparing the addresses of the objects, the other comparison operators appear to compare the numeric values. For instance the following code snippet: ``` Integer a = new Integer(3000); Integer b = new Integer(3000); 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)); ``` produces ``` a < b false a <= b true a == b false a >= b true a > b false ``` Which appears to indicate all operators but == compare the value, not the address of the object. Is it accepted usage to use the <= class of operators, or just an unsupported feature of my compiler or something?

Original source

Related problems