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 strings and string pool Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "strings and string pool" Watch "strings and string pool" New topic
Author

strings and string pool

Vinney Shanmugam
Ranch Hand

Joined: Aug 27, 2008
Posts: 104
what is the difference between declaring,

String test = "string testing";

and

String test = new String("string testing");
Devaka Cooray
Saloon Keeper

Joined: Jul 29, 2008
Posts: 2691
    
    3

You have mentioned the difference in the subject line.
In other words, the second statement always create a NEW String object, while the first statement may take an existing String object from the String pool.


Author of ExamLab (Download) - the free mock exam kit for SCJP / OCPJP
Home Page -- Twitter Profile -- JavaRanch FAQ -- How to Ask a Question
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

Even worse, the second line does both. It takes a string out of the string pool (creating it if necessary) and then creates an exact copy of it. The String API also mentions this:
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32604
    
    4
Rob Prime wrote: . . . The String API also mentions this . . .
Vinney Shanmugam, you should by now be used to looking in the API documentation. And noticing where the documentation tells you not to use a construct.
 
I agree. Here's the link: jrebel
 
subject: strings and string pool
 
Similar Threads
K&B page 448 Question on GC
practice question: what is the output?
Split a string
Doubt about creating a instance for String class
Query Regarding String ???