Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings pool in Java.

 
Prashant Neginahal
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Every body,
Case 1:
String str1="Hello";
In above line, String object is created in String pool and 'str1' will get reference to that object.
Case 2:
String str2=new String("Hi");
In another case here, instace is created in program space and 'str2' will get reference to that object.
My question is ,in second case, Will the instace is created in pool also apart from program space?
Thanks, hope i get the answer....
Prashant Neginahal.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case one the String Literal will be added to the Constant Pool.
If you do something like:
String str2=new String(args[0]);
the String will be created as an object on the Heap where all the other objects live. If you WANT to force the String object into the constant pool you can do:
str2.intern();
In the example that you gave for case 2 you created a String literal and THEN used it to create a String object. Literals are interned for you, so yes this would also be in the String Pool (which is part of the Constant Pool). In real life this is not a good thing to do. Very wasteful.
From the JLS 3.10.5 String Literals
Literal strings within the same class (�8) in the same package (�7) represent references to the same String object (�4.3.1).
Literal strings within different classes in the same package represent references to the same String object.
Literal strings within different classes in different packages likewise represent references to the same String object.
Strings computed by constant expressions (�15.28) are computed at compile time and then treated as if they were literals.
Strings computed at run time are newly created and therefore distinct.
The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

[ December 10, 2002: Message edited by: Cindy Glass ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic