Search code examples
javawrapperprimitive

Integer v/s int


Read this on the oracle docs java.lang page:

Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose.

I'm not sure I understand why these are needed. It says they have useful functions such as equals(). But if I can do (a==b), why would I ever want to declare them as Integer, use more memory and use equals()? How does the memory usage differ for the 2?


Solution

  • Java's generics system only supports class types. And since primitives are not classes, they can't be used with generics. However, a primitive's wrapper class can be used as a generic type. For example, you may not declare an ArrayList<int>, but you can achieve a similar functionality with an ArrayList<Integer>.

    It is also of occasional use to initialize a variable's value to null. Primitives, however, cannot be set to null; that privilege is reserved for objects.

    // This is OK
    Integer iDontKnowValueYet = null;
    
    // Compile error!
    int iDontKnowThisYetEither = null;