hi Maggie,
first of all
you should not use quote tags when you want to say or ask something. you should use only to refer to something.
now, Lets come to your question.
First thing you should fit in your mind is whenever you see new keyword that means that jvm is bound to create a new object on heap.
now about Strings:
I am sure you know Strings are immutable and there is a
string constant pool where string literals are stored.
you can create string in two ways:
First way:
so whenever you create a string this way jvm first looks into the constant pool if it finds a string literal "abc" it assigns it to variable 's' but if it doesnot find one it will create a new string literal in the pool and variable 's' will refer to newly created literal.
Second way:
In this case since there is new keyword jvm will create a String object on heap and rest of the procedure is same as the first way that is it will find the string in constant pool and if cant find it will create a new literal in the pool and assign it to newly created String object.
this is for String Now lets move to wrapper classes.
for wrappers like Integer, also there is a constant pool which ranges from -127 to 128. And they also have two ways similar to String class.
while creating them the first way if you assign them the value that is from the constant pool range no new object is created but if you assign them value that isn't from the range for eg. if the value is -547 or 300 then a new object will be created.
again the second if you create them using new keyword a new object will always be created on heap no matter you assign it a value from constant pool or not.
now if you create a object like in the following line:
you can see, 'new' has been used thrice here so 3 new objects created on heap.
I hope the concept is now clear to you, If you have any further query you can ask.
