Reputation: 149
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?
Upvotes: 0
Views: 176
Reputation: 719238
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:
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
Upvotes: 1
Reputation: 31
2 Objects will be created .. one boolean object and one integer object residing in the heap memory.
Upvotes: 0
Reputation: 2314
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
Upvotes: 1