i want to ask whether how are objects created in this program....
If its String objects......
and you say String x="Java";
here one reference variable x and one object "Java" is created.....
then when we say
String d=new String("Java");
here one reference variable d and two objects are created is Java which goes to heap and one goes to string pool.....
what when wrapper objects are created like Integer w=100;
and Integer q=new Integer(100);
how many objects are created here in both the lines and if we have
class called like mentioned above....
suppose named as Gc
we say Gc g=new Gc(new Gc(new Gc(null)))
Gc g=new Gc(new Gc(new Gc));
how many objects are created and how do you refer to those objects...have you understood my question???
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:
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.
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.