Search code examples
javaobjectprimitive

How come primitives can skip "new Object" instantiation in Java?


For example if you have an integer:

int i = 9;

How can it do that? I mean the full syntax is:

int i = new Integer(9);

How does it skip the whole new Integer() part and still work?

Thanks.


Solution

  • new Integer() is not a primitive; it's a boxed primitive.
    Actual primitives (int, etc) are not objects and cannot be instantiated.

    Note that you can also write Integer x = 9, and the Java compiler will implicitly insert new Integer().
    This is called auto-boxing.