-2

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?

  • https://stackoverflow.com/questions/17489250/how-can-a-string-be-initialized-using – Suresh Atta Jan 18 '20 at 15:05
  • Because those are different objects, even if they represent same text. "Is concat function not saving the String object in string constant pool?" that is correct. Why would it? Point of string pool is to cache reusable strings, like in case of `for (..){ print("foo");}` we can reuse "foo" instead of recreating it in each iteration. But now lets assume we have `for(int i=0; i – Pshemo Jan 18 '20 at 15:07
  • "*Is concat function not saving the String object in string constant pool?*" - Apparently, it is not. – Turing85 Jan 18 '20 at 15:17
  • 1
    T.J. Crowder's answer is the correct one as it addresses your direct question – Hovercraft Full Of Eels Jan 18 '20 at 15:17
  • Also note that relying on reference equality subtly makes you code vendor dependent as the rules for what to intern and when are not rigidly set in stone. – Thorbjørn Ravn Andersen Jan 18 '20 at 16:03

1 Answers1

3

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875