1) using new operator:- String st=new String(“abc”);
2) Without using new operator:- String st=”abc”;
Once string object is created with or without new operator contents of string object cannot be modified. But we can modify String reference variable. when you are trying to modify string objects ie.. concatinating,repalcing etc.. a new string object will be created every time.
Creating new object every time consumes more memory. To solve this problem sun introduce String Constant Pool mechanism.When you creating string object with new operator a new string will be created every time. It does not use string constant pool.When we are creating string object without new operator following things happened.
a) JVM will check whether the string constant is available in the pool or not.
b) If it is available in the pool same object referece will be assigned to new reference variable.
c) If string constant is not available in the pool a new constant will be created and will be assigned to new reference variable and also placed this new constant in pool.
Thanks! brief and very instructive.
Suppose we compile and run the following code.
public class test {
public static void main(String args[]) {
String s1 = “abc”;
String s2 = new String(“abc”);
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
What is the output ? Also provide the explanation for it.
@seeker, sry for the late reply. Here is the ans.
== operator checks the address of the variables. In above case, s1 & s2 will definitely will have different addresses as s2 is created with new operator as mentioned above.
equals checks the contents as well as hashcode of the variables.
But, default behavior is same as == though unless you override hashcode or equals methods. default implementation of hashcode is generated out of address & some other info. So, in this case also, no match. Contents will be matched in this case.Answer would be 2 & 3. [Modified, thanks to anil to find it out.]
– Pavan
2 and 3 are the answers
@anil, you are correct.
– Pavan
Great Explanation