-2

I have been reading about autoboxing in Java. I wanted to know the difference between the below two

 1) int y = 9;
    Integer x = y;

and

2) Integer x = new Integer(9);

What is the difference between the above two ? I know second allocates a memory in heap. Does first case not allocate space in heap?

sammy
  • 31
  • 3
  • 2
    I think the answer to your question is actually found at https://stackoverflow.com/q/20877086 - pay particular attention to higuaro's answer, which is currently fourth from the top, and also my answer (second from the top). – Dawood ibn Kareem Jan 28 '21 at 18:30
  • One difference is the first uses autoboxing while the second uses explicit boxing. – Ole V.V. Jan 28 '21 at 19:17

1 Answers1

2
Integer x = y;

Actually results in

Integer x = Integer.valueOf(y);

rather than

Integer x = new Integer(y);

For ints in the range -128..127, this will return a cached value. Outside that range, it may use either a cached value or a new Integer, depending upon your JVM and configuration.

By using a cached value for common ints, unnecessary heap allocations are avoided. new always results in a new instance being created (provided no exception is thrown).

Andy Turner
  • 122,430
  • 10
  • 138
  • 216
  • 1
    The impact might be more than just caching. By using the factory method, you are explicitly saying that you don’t care about the object identity. This enables optimizers to rewrite the code at runtime to work with the value itself, without the need for Escape Analysis. – Holger Jan 29 '21 at 09:22