File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes All about Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "All about Strings" Watch "All about Strings" New topic

All about Strings

Manish Chhetri

Joined: Oct 31, 2003
Posts: 11
What is the difference between String x="hello"; and String x=new String("hello") in terms of the object creation and the reference. Is there any difference in the way memory is allocated for these two type of String declarations.

The One..
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Welcome to JavaRanch!
In the first case (without the new) the String comes from a pool of unique strings held internally by the JVM; literal Strings are put into this pool when the classes defining them are loaded. In the second case, a new String object is allocated at that point while the program is executing.

[Jess in Action][AskingGoodQuestions]
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
All string constants are dumped into the CONSTANT_POOL at compile time. In the following example:

When this compiles there are two string constants placed in the constant pool, one for "A string" and one for "B string". However at runtime both 'one' and 'two' would reference the same string, while new string instances would be created for 'three', 'four' and 'five', as Ernest pointed out.
So "one == two" would evaluate to "true", but any other combination of strings would evaluate to "false" when doing an "==". That's why it's always safest to use ".equals()" when doing string comparison, unless you actually want to see if the two strings reference the same underlying String instance.
I agree. Here's the link:
subject: All about Strings
It's not a secret anymore!