These types are not treated as objects in Java and are represented by their bit representations. All other types are objects, represented by a reference to them, that is, by a machine address or a pointer. Each primitive type has a corresponding wrapper class that will hold the type as an object with a reference to it. The wrapper classes for primitive types are: Boolean, Character, Byte, Short, Integer, Long, Float, and Double.
For example, the Integer type holds an int value, but it is an object with named constants and methods, and it can be handled like other objects.
If we have a int, such as int num = 47;, this can be converted to Integer type using
Integer numWrap = new Integer(num);
Given an Integer such as numWrap
above (just an arbitrary name), there are various methods
that can be used: numWrap.valueOf() returns the
value 47. The method
numWrap.toSting() converts the value to a String
(though this can be done simply by numWrap + "").
More importantly, there is a method that corresponds to the
comparison operators: for two variables num1Wrap
and num2Wrap of type Integer,
one can write
num1Wrap.compareTo(num2Wrap)
The result is > 0 in case num1 > num2,
is < 0 in case num1 < num2, and == 0
in case num1 == num2, where num1
and num2 are the ints corresponding
to num1Wrap
and num2Wrap.
Given an int inside an Integer wrapper class, it can be handled like other objects.
public interface Comparable {
public int compareTo(Object x);
}
A class implements Comparable by supplying code for
this compareTo method.
Note that obj1.compareTo(obj2) < 0 means
that obj1 is less than obj2.
Similarly, obj1.compareTo(obj2) > 0 means
that obj1 is greater than obj2,
and obj1.compareTo(obj2) == 0 means
that obj1 is equal to obj2.
The Comparable interface is already implemented
for the wrapper classes of primitive types as well as for
String, so that Comparable is
available for these classes.
I have created a sheet comparing the code for the original version of the List class (the one with an interface, but hardwired for integers) with the version that uses Comparable types: In Postscript In PDF
Here is another sheet comparing the four different main methods in the examples above: In Postscript In PDF