Changes in the Java language have blurred the functions of
java.lang.Integer. However, every Java developer should
understand the distinction between the two.
Confusion arises because the two sets of code in the method below seem to be the same:
The code produces the following output:
2 true 2 true
However, very different things are going on under the covers
int is a number; an
a pointer that can reference an object that contains a number.
The differences become apparent if you convert the code to an older version of Java (this will still work in Java 5 and above, of course).
It is easy to see how the Java 5 compiler allows developers to simplify the syntax.
The second code block has a problem that is not immediately apparent, but can be seen if we rewrite the code slightly.
Now the output of the code becomes:
2 true 2 false
== operator is used to test two reference
variables, it tests to see if they point to the same object. By
explicitly using the
new operator to ensure that
y point to different objects,
false. We are fooled because
returns the same object for a small range of integers. The
method must be used to check for object equivalence. The correct way to
check the equivalence of two
Integers looks like this:
It should be obvious that using
arithmetic involves more CPU cycles and consumes more memory.
What is Integer useful for?An
intis not an object and cannot passed to any method that requires objects. A common case is in using the provided collection classes (
Set) - though it is possible to write versions of these classes that provide similar capabilities to the object versions. The wrapper classes (
Double, etc) are frequently required whenever introspection is used (such as in the reflection API).