3

I know that using most of String's methods will return a new string object which is added to the string pool and that the string literals passed as arguments to these methods also are added to the string pool.

For example the code below will create three string objects namely: "Hello ", ""World!"" and "Hello World!" which are added to the string pool implying that the argument passed to concat() method is added to the string pool.

What I am curious to know whether the string literal arguments passed to StringBuilder.append() method and any other methods in StringBuilder are added to the string pool.

Or maybe I should ask whether all string literal arguments that are passed to any other method in any other class also are added to the string pool ?

I also want to add the I know these facts based on java 6.

String s = "Hello " ;
s = s.concat("World!") ;
user9349193413
  • 1,203
  • 2
  • 14
  • 26
  • I think you use the term "string pool" wrong. Your code will add 3 String objects to the heap and remeber two of them in the String pool (while loading the class). – eckes Aug 10 '14 at 19:42

3 Answers3

4

What I am curious to know whether the string literal arguments passed to StringBuilder.append() method and any other methods in StringBuilder are added to the string pool.

Or maybe I should ask whether all string literal arguments that are passed to any other method in any other class also are added to the string pool ?

All String literals are put into the string pool. How you use the literal is irrelevant.

Community
  • 1
  • 1
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
3

None of String methods (beside intern()) will fill the String pool. And none of the methods of StringBuilder do that. Literals are added while the class is loaded to the contant pool. So if your invoke the concat() it gets a interned constant object reference. But concat is doing nothing to intern it or nothing which depends on it beeing interned.

eckes
  • 10,103
  • 1
  • 59
  • 71
1

From java 1.7 :-

 public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }

Unless you use String.intern() or String literals you are not adding it to the String pool

Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35