简体   繁体   中英

How many objects created by JVM

If we use

Boolean boolean = new Boolean(true);

and

Integer integer = new Integer(10);

then how many objects are created and where do they reside?

In your code you would end up with 1 instance of Integer which is referred to by integer and 1 instance of Boolean which is referred to by boolean . The instances will be created on the heap.

See: int vs Integer

How many objects are created and where do they reside?

  • Two objects created. Each new will create a new object.

  • All Java objects reside in the heap... so they reside in the heap.

In the other hand, if you use int instead of Integer and boolean instead of Boolean then:

  • No objects are created.

  • The values true and 10 will be in the variables... and will therefore reside wherever the variables reside. That will depend on what kind of variables they are.

Finally, consider this version:

Boolean boolean = true
Integer integer = 10;

The difference between this and your original version is that two values are produced by auto-boxing. This will EITHER create new objects OR reuse objects that have been created before, and have been cached. (It depends on the type, the JVM implementation, and the in some cases the cache size configured by JVM options.)

So the answers will be:

  • Zero, one or two objects will be created, depending on the above factors.
  • The objects will be in the heap (as before).

Note: auto-boxing obtains the objects by calling the wrapper classes valueOf method. You can call it explicitly in your own code as an alternative to autoboxing. It is better to do this than to use new .

Integer i1 = new Integer(10);      // bad - generates an unnecessary object
Integer i2 = 10;                   // good - auto-boxing uses (may use) cached object
Integer i3 = Integer.valueOf(10);  // equivalent to auto-boxing

2 Objects will be created.. one boolean object and one integer object residing in the heap memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM