0

I know that line one is the same as line two in the code below

  String s1 = new String("a") + new String("b");
  String s2 = new Stringbuilder().append("a").append("b").toString();

But I'm unsure whether either version will put the resulting string "ab" into the string constant pool.

Does new String("ab") create a new object or does it just return "ab" from the constant pool?

  String s3 = new String("ab");
10
  • See this stackoverflow.com/questions/15746018/… Commented Dec 10, 2018 at 9:12
  • @shanbhagsv The accepted answer there is dated 2013. It could be outdated, considering there were some changes in String pool. Commented Dec 10, 2018 at 9:16
  • String s1 = "Pool"; String s2 = new StringBuilder().append("Po").append("ol").toString(); System.out.println(s1==s2); //False so nothing was changed from 2013 Commented Dec 10, 2018 at 9:18
  • 1
    @Teddy what changes in the String pool are relevant here? a new will always create a new Object, compile-time constant Strings are still added to the constant pool and a StringBuffer still does not intern anything. Commented Dec 10, 2018 at 9:18
  • @Thilo I agree the change is only distantly related. It is indirectly related. In those days we needed to worry about constant pool because it was not GCed. Now the question is immaterial because constant pool is GCed ;) Commented Dec 10, 2018 at 9:24

1 Answer 1

2

To answer your question whether it will put String "ab" into string constant pool when stringbuilder.toString() was used to return a new string

No string builder will not create any object inside string constant pool

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.