Wednesday, February 07, 2007

int vs. Integer

int is a primitive data type in Java along with double, long, float, char, byte, boolean and short.

java.lang.Integer is an OO wrapper class which allows int to be used in situations where an object is required, in Collections for example.

Integer is more convenient because of various methods available with the class, however the conversion of an int to Integer is expensive, and therefore int should be used where faster performance is required.

Java 5 introduces the Autoboxing feature to automate the process of boxing an int into an Integer and unboxing the Integer to an int. This allows you to largely ignore the distinction between int and Integer except:

  • Integer can have a null value and trying to autounbox null will throw a NullPointerException
  • == performs reference comparisons with Integer and value equality comparisons on int
  • There are still performance costs associated with automatic boxing and unboxing

No comments: