2

Let's say that I have a class:

class A {
  private Integer i;

  public int getI() {
    return i;
  }

  // Setter, etc.
}

and I write:

A a = // initializer

Integer b = a.getI();

how many Integers will there be? My naive reading about autoboxing/unboxing leads me to believe that the answer is 2, but if getI() were:

public Integer getI();

then the answer would be 1.

joeblubaugh
  • 1,127
  • 7
  • 10

2 Answers2

3

You are absolutely correct, with one caveat: the answer to the first part depends on the value of Integer i.

  • In the first scenario, one Integer is created in the constructor, and the other one is created when boxing the int coming from getI()
  • In the second scenario, there needs to be no boxing, so there's only one Integer object.

Note: if the value of the Integer i is small (more precisely, between -128 and 127, inclusive), autoboxing will produce the same Integer through interning.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Ah, interning too! A small followup: Is it safer to use the first style? If I use the second style and later make another assignment to b, will a.i remain the same or be updated too? – joeblubaugh Dec 11 '13 at 22:14
  • @joeblubaugh Both ways are safe: `java.lang.Integer` is *immutable*, so it cannot be updated "behind your back". – Sergey Kalinichenko Dec 11 '13 at 22:18
1

Correct....ish

It's theoretically possible the Compiler/JIT/JVM/etc could optimise out the autoboxing but I've no idea if it actually would.

It's also possible the same Integer object would be re-used. For example Integer.valueOf(2) is guaranteed to give you the same Integer object every time you call it and re-use the same object. This is only guaranteed for values in the range -128 to +127 inclusive though, it may happen outside that range but should not be relied upon.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • 1
    Actually it *is* guaranteed between -128 and 127 inclusive. See near the end of http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7 – Jon Skeet Dec 11 '13 at 21:58
  • The Java Compiler does not make that much optimisation, because this will reduse the benefit of the JIT. – Christian Kuetbach Dec 11 '13 at 21:58
  • Yes, by compiler I meant Just In Time compilation too, could have been clearer. @Jon that's nice to know - I knew it was the usual case wasn't aware it was required. – Tim B Dec 11 '13 at 22:00