If we talk about the Strings in Java ,its very interesting topic and really important .
Lets discuss how to create String object in Java.
There are two ways for this.
1. by using a String Literal and
2. by using a new Keyword.
First discuss about using String Literal-
If we create an String object like
In this case only one String object will create in 'String Constant pool' and reference of that newly created object "khemraj" will be given to
reference variable s.
if you again create a String object using the same String Literal "khemraj" then the jvm will check the 'String constant pool' that Is there any existing object with the same literal?
if it already exist then it will not create any new object and will provide the same reference to this also. otherwise it will create a new object.
Now discuss creating String object Using new Keyword -
If you create a String object like this-
String s1=new String("khemraj");
In this case two objects will be created.
one in a 'String Constant Pool' and another in the Heap Memory. and s1 will contain the reference of object created in Heap Memory.
what will happen if you again create String object using the same -
String s2=new String("khemraj");
In this case only one object will be creat and that will be in Heap and reference of this newly created object in Heap, will be provide to s2. Not any object will be create in 'String Constant Pool' because there is already an object present with the same value "khemraj" .