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 Wich is the different Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Wich is the different" Watch "Wich is the different" New topic

Wich is the different

Carlos rodriguez

Joined: Apr 14, 2004
Posts: 2
Dear Mr.
I need your help, to understand the following aspect of String in Java.
I dont understand, Why when I write:

String x, y;


Java, create a same instance of the String Object.
but, when I write

x=new String("Mother");
y=new String("Mother");
Java create a diferent instance of the String Object.

Thanks for your help
Carlos A Rodriguez C
Sanju Thakur

Joined: Sep 16, 2003
Posts: 3
For this you will need to understand that String is immutable. It maintains a pool of literal strings and simply refers to that. When someone changes the string value, it will abandon that literal, create a new literal and will start referncing it.
When u simply say
it just references any "Mother" in the pool, if not it will create a new "Mother" and refer it.
But when you say "new", you are effectively forcing the JVM to refer to a new literal whether an equivalent literal exists in the pool or not (which actually is a waste of memory)
I agree. Here's the link:
subject: Wich is the different
It's not a secret anymore!