In Java, there are wrapper objects which contains just a single primitive type. They are Integer, Double, Character, Boolean, Byte, Short, Long, Float
, which boxes the int, double, char, boolean, byte, short, long, float
primitive types respectively.
For most objects, they cannot be compared, but you can implement Comparable
or Comparator
so you can define when one object of a given type (call it Ty
) is less, equal, or greater than another object of the same type Ty
. However, if so, you test inequality by using compareTo(Ty oth)
or compare(Ty arg0, Ty arg1)
, both returning int
, representing less than if return value < 0, and vice versa.
However, for numeric Wrapper objects (including Character
), you can actually compare these objects using inequality relational operators for primitives <, <=, >=, >
as in this code below:
Integer a = 15;
Integer b = 0;
Double x = 7.5;
Double y = 15.000000000000000000000000001; // Decimal part discarded
Character ch = 'A';
System.out.println(x + " < " + a + " is " + (x < a));
System.out.println(x + " < " + b + " is " + (x < b));
System.out.println(a + " > " + b + " is " + (a > b));
System.out.println(ch + " <= " + 65 + " is " + (ch <= 64)); // 'A' has ASCII code 65
System.out.println(ch + " <= " + 65 + " is " + (ch <= 65));
System.out.println(a + " >= " + b + " is " + (a >= b));
Which outputs
7.5 < 15 is true
7.5 < 0 is false
15 > 0 is true
A <= 65 is false
A <= 65 is true
15 >= 0 is true
Note that between two objects, ==
and !=
always work and respectively denote reference equality and inequality instead. It is not part of the question.
Is "operator overloading" of these wrapper functions unique to the wrappers?