File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes String  Pool Vs  String new operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "String  Pool Vs  String new operator" Watch "String  Pool Vs  String new operator" New topic
Author

String Pool Vs String new operator

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1367
String str1 = "how are you";

String str2 = new String("how are you");

Whether String Str1 will refer string poll for Str1 exists in the pool or not. If exists, then this will return the reference, If not exist, will it create new object like new operator ?
String str2 never refer the string pool because it is created by new operator(creates new String object in the heap). Which one is memory efficient ?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18115
    
    8

Is it more memory-efficient to use an existing object from a pool, or to create a new object which is a copy of one from the pool?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36464
    
  15
Have you seen what it says in the API about that String constructor?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Obviously the first statement is more memory efficient. Both use the same String from the String pool, but the first one uses only this object; the second one makes an exact copy of it and uses that. With String being immutable, that's completely superfluous. That's why the API discourages using that constructor, as Campbell's link indicates.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String Pool Vs String new operator
 
Similar Threads
equals and ==
string comparision problem
difference between two string object
Need some Help
String comparision