Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many objects are created by using the Integer wrapper class?

Integer i = 3;  i = i + 1;  Integer j = i;  j = i + j;  

How many objects are created as a result of the statements in the sample code above and why? Is there any IDE in which we can see how many objects are created (maybe in a debug mode)?

like image 704
Syamesh K Avatar asked Mar 17 '16 10:03

Syamesh K


2 Answers

The answer, surprisingly, is zero.

All the Integers from -128 to +127 are pre-computed by the JVM.

Your code creates references to these existing objects.

like image 142
Bathsheba Avatar answered Oct 06 '22 04:10

Bathsheba


The strictly correct answer is that the number of Integer objects created is indeterminate. It could be between 0 and 3, or 2561 or even more2, depending on

  • the Java platform3,
  • whether this is the first time that this code is executed, and
  • (potentially) whether other code that relies on boxing of int values runs before it4.

The Integer values for -128 to 127 are not strictly required to be precomputed. In fact, JLS 5.1.7 which specified the Boxing conversion says this:

If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1) ... then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

Two things to note:

  • The JLS only requires this for >>literals<<.
  • The JLS does not mandate eager caching of the values. Lazy caching also satisfies the JLS's behavioral requirements.

Even the javadoc for Integer.valueof(int) does not specify that the results are cached eagerly.

If we examine the Java SE source code for java.lang.Integer from Java 6 through 8, it is clear that the current Java SE implementation strategy is to precompute the values. However, for various reasons (see above) that is still not enough to allow us to give a definite answer to the "how many objects" question.


1 - It could be 256 if execution of the above code triggers class initialization for Integer in a version of Java where the cache is eagerly initialized during class initialization.

2 - It could be even more, if the cache is larger than the JVM spec requires. The cache size can be increased via a JVM option in some versions of Java.

3 - In addition to the platform's general approach to implementing boxing, a compiler could spot that some or all of the computation could be done at compile time or optimized it away entirely.

4 - Such code could trigger either lazy or eager initialization of the integer cache.

like image 37
Stephen C Avatar answered Oct 06 '22 03:10

Stephen C