Search code examples
javastringconcatenation

Why 2 String created using concat function and same strings are having object reference different?


My Code :

class TestStringConcatenation{
 public static void main(String args[]){

   String s1="Sachin ";
   String s2="Tendulkar";

   String s3=s1.concat(s2);
   String s4=s1.concat(s2);

   System.out.println(s4==s3);
  }
}

Output :

false

Is concat function not saving the String object in string constant pool?


Solution

  • Is concat function not saving the String object in string constant pool?

    It's not storing it in the intern pool, no. (The constant pool is a different thing.) Only string constants are automatically interned. If you want any other string interned, you have to do it explicitly, via a call to intern.