This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes String Pooling & String Constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Pooling & String Constructors" Watch "String Pooling & String Constructors" New topic
Author

String Pooling & String Constructors

Souvik Goswami
Greenhorn

Joined: Jan 17, 2012
Posts: 9

String Pooling-Its the use a pool of strings for the reusability.

Now,

Question 1) Which String constructor out of the two calls for pooling???

1. String s="abc"; or,
2. String s=new String("abc");


Question 2) If String "abc" is already in a String pool with reference(say s1), then how
will it be used for another reference(say s2)?

In other words, how is two String references(s1,s2) pointing to same content("abc") is achieved??




Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Souvik Goswami wrote:String Pooling-Its the use a pool of strings for the reusability.

Now,

Question 1) Which String constructor out of the two calls for pooling???

1. String s="abc"; or,


The String "abc" is already in the pool before we get to this line. It was put into the pool when the class was loaded, if it wasn't already there.
This line just gets a reference to that String object and copies that reference into variable s.

2. String s=new String("abc");

The String "abc" is already in the pool before we get to this line. It was put into the pool when the class was loaded, if it wasn't already there.
This line gets a reference to that String object and passes it to String's new String(String) constructor, and a new String object is created, with a copy of the characters from the "abc" String that was in the pool.



Question 2) If String "abc" is already in a String pool with reference(say s1), then how
will it be used for another reference(say s2)?

In other words, how is two String references(s1,s2) pointing to same content("abc") is achieved??


The same way it is any time you do referenceVaraible1 = refrenceVariable2. The value the reference is just copied into the variable.


Souvik Goswami
Greenhorn

Joined: Jan 17, 2012
Posts: 9

Okay Jeff I agree with you. If that is true then why is,

Question 1)

String s = "abc";
String s1 = new String("abc");
System.out.println(s == s1);


not TRUE?

If "abc" is already in the pool, then both must get the same reference.


Ouestion 2)
String a="a";
String b="ab";

a+="bc";
b+="c";
System.out.println("a==b"+(a==b));


not TURE?

Likewise, here "abc" should be getting stored in pool prior to the line
b+="c";



[Thumbnail for String.png]

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14116
    
  16

Souvik Goswami wrote:Okay Jeff I agree with you. If that is true then why is,

Question 1)
....
not TRUE?

Because:
Jeff Verdegan wrote:This line gets a reference to that String object and passes it to String's new String(String) constructor, and a new String object is created, with a copy of the characters from the "abc" String that was in the pool.


About Question 2: No, "abc" is not stored in the string pool when you concatenate strings together like that. Only string literals ("a", "ab", "bc", "c") are stored in the string pool. The compiler is not going to evaluate statements like a += "bc"; at compile time and store the result in the string pool.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Souvik Goswami wrote:Okay Jeff I agree with you. If that is true then why is,

Question 1)

String s = "abc";
String s1 = new String("abc");
System.out.println(s == s1);


not TRUE?

If "abc" is already in the pool, then both must get the same reference.


No, it must not. You're assuming every single String goes into the pool. It doesn't. The new operator always creates a new object. So now we have two String objects--the one in the pool and the newly created one that has the same contents but is not in the pool.


Ouestion 2)
String a="a";
String b="ab";

a+="bc";
b+="c";
System.out.println("a==b"+(a==b));


not TURE?

Likewise, here "abc" should be getting stored in pool prior to the line
b+="c";



Nope. Again, you're incorrectly assuming that all Strings go to the pool. That is not the case. Try this though:



And in the future, please UseCodeTags(⇐click) when posting code.
Souvik Goswami
Greenhorn

Joined: Jan 17, 2012
Posts: 9

Okay. So, as far as I understood
  • String pool stores String Literals rather than String Objects
  • The code
  • just makes the String reference s point to literal "abc" in the pool
  • While,
  • actually creates a String Object, pointed by String reference s with its contents copied from the literal "abc" in pool
  • In String operations like (concat, charAt, toUpper, etc.), only literals used are pooled and not results


  • Please do correct me if my understanding is wrong.
    Jeff Verdegan
    Bartender

    Joined: Jan 03, 2004
    Posts: 6109
        
        6

    Souvik Goswami wrote:Okay. So, as far as I understood
  • String pool stores String Literals rather than String Objects


  • The constant pool stores String objects. Which String objects go there are:
  • String literals from source code.
  • Compile-time String constants that are constructed from one or more literals plus other compile-time String constants, such as "abc" + "def"
  • Any String on which you call intern().
  • I think things like class names and method names go there too, but not 100% sure.


  • And note that only one copy of any given String will go into the pool.

    Also, I think the constant pool is where cached values of wrapper objects--such as Integers from -128 to 127--are stored.


  • String s="abc" just makes the String reference s point to literal "abc" in the pool


  • Correct.

  • String s=new String("abc") actually creates a String Object, pointed by String reference s with its contents copied from the literal "abc" in pool


  • Correct.

  • In String operations like (concat, charAt, toUpper, etc.), only literals used are pooled and not results


  • The results aren't pooled because they're not compile-time constants. Anything passed to these methods follows the same rules as above--if it's a compile-time constant, it's pooled, and if not, it's not. But that has nothing to do with these String operations in particular. It's the same for any method call.
    Souvik Goswami
    Greenhorn

    Joined: Jan 17, 2012
    Posts: 9

    Thanks Jeff and Jesper for clearing this concept.
    dennis deems
    Ranch Hand

    Joined: Mar 12, 2011
    Posts: 808
    Souvik Goswami wrote:
  • String pool stores String Literals rather than String Objects

  • A String literal is a String object.
    Jeff Verdegan
    Bartender

    Joined: Jan 03, 2004
    Posts: 6109
        
        6

    Dennis Deems wrote:
    Souvik Goswami wrote:
  • String pool stores String Literals rather than String Objects

  • A String literal is a String object.


    Since I'm feeling extra nitpicky at the moment, I'll point out that a String literal in source code translates to a String object at runtime.



    But, yeah, your point stands--there is no "String literal vs. String object" dichotomy.
    Souvik Goswami
    Greenhorn

    Joined: Jan 17, 2012
    Posts: 9

    Okay Jeff,
    So, the bottom-line is "If its a constant, objectify and then pool it".
    Mohana Rao Sv
    Ranch Hand

    Joined: Aug 01, 2007
    Posts: 485



    Even we can point to string pool when we are using new keyword, by intern method. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.


    ocjp 6 — Feeding a person with food is a great thing in this world. Feeding the same person by transferring the knowledge is far more better thing. The reason is the amount of satisfaction which we get through food is of only one minute or two. But the satisfaction which we can get through the knowledge is of life long.
    Joanne Neal
    Rancher

    Joined: Aug 05, 2005
    Posts: 3502
        
      13
    Mohana Rao Sv wrote:

    Even we can point to string pool when we are using new keyword, by intern method. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    Which is basically identical to except that a new String object is created which becomes immediately available for garbage collection.


    Joanne
    Souvik Goswami
    Greenhorn

    Joined: Jan 17, 2012
    Posts: 9

    Quick question



    Now, Line 1 creates a String reference s which points to String Object "abc" which is in String Pool
    Line 2 creates a String reference t which points to a String Object whose contents are copied from the pooled String "abc".

    My question is where does the object, that t points to, resides?

  • String pool doesn't allow duplicacy
  • At the same time "abc" is a String constant
  • Jeff Verdegan
    Bartender

    Joined: Jan 03, 2004
    Posts: 6109
        
        6

    Mohana Rao Sv wrote:

    Even we can point to string pool when we are using new keyword, by intern method.


    That has nothing to do with the new operator. That's true of any String object. We're still creating a new String object here, just like before. It's just that immediately afterwards, we check to see if there's already an entry in the pool that matches that newly created String, add one if not, and then assign the reference to the pooled object to str2, instead of the reference to the new object.
    Jeff Verdegan
    Bartender

    Joined: Jan 03, 2004
    Posts: 6109
        
        6

    Souvik Goswami wrote:Quick question



    Now, Line 1 creates a String reference s which points to String Object "abc" which is in String Pool


    We don't usually talk of references being "created". If that's a local variable, then the variable is "created" on the stack when the method is entered. If it's a member variable, then the variable is "created" when the defining object is instantiated. That line just assigns a reference value to the already created variable.

    But, yes, all that happens on that first line is that a reference to the "abc" variable in the constant pool is copied into variable s.

    Line 2 creates a String reference t which points to a String Object whose contents are copied from the pooled String "abc".


    Subject to my above comments about creating references, yes, as already stated, variable t gets a reference to the newly created String object.

    My question is where does the object, that t points to, resides?


    In the heap, with the rest of the non-pooled objects.

  • String pool doesn't allow duplicacy
  • At the same time "abc" is a String constant


  • "abc" is a compile-time constant, and therefore is pooled. A String created with the new operator is not a compile-time constant (even if it was copied from one), so it does not go into the pool.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 38509
        
      23
    Has nobody mentioned Corey McGlone’s JavaRanch journal article in this thread? That will answer lots of your questions.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: String Pooling & String Constructors