Reputation: 6023
AFAIK the following code...
void foo () {
Integer i1 = new Integer(2);
Integer i2 = new Integer(2);
Integer i3 = new Integer(2);
i3 = i1 + i2;
}
... will actually create a new Integer Object when executing the + operator and assign its address to i3.
Does the same hold for primitive types also? I.e.:
void foo () {
int i1 = 2;
int i2 = 2;
int i3 = 2;
i3 = i1 + i2;
}
... Or will i3 in this case keep it's address in memory and get's the result of i1 + i2 copied to that address?
Thank you in advance.
Upvotes: 2
Views: 94
Reputation: 200148
Let me answer by turning your question a bit upside-down:
Integer i1 = new Integer(2);
Integer i2 = new Integer(2);
Integer i3 = new Integer(2);
i3 = i1 + i2;
vs.
int i1 = 2;
int i2 = 2;
int i3 = 2;
i3 = i1 + i2;
In both cases the exact same thing happens to the i3
variable: its value gets overwritten and its address stays the same. The only difference is in the meaning of those values.
NB. Since the Integer
instances you use don't escape the method, the actual native code may not make any allocations at all and may be exactly equivalent in both cases.
Upvotes: 1
Reputation: 1500235
Your terminology is a bit confused.... the value of i3
isn't an address (or reference) at all, it's just the integer value. But no, the example you've given won't create any Integer
objects.
Upvotes: 3