aspose file tools*
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Wich is the different" Watch "Wich is the different" New topic
Author

Wich is the different

Carlos rodriguez
Greenhorn

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;

x="Mother";
y="Mother";

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
Atentamente
Carlos A Rodriguez C
cajualin@epm.net.co
rcarlos@upb.edu.co
Sanju Thakur
Greenhorn

Joined: Sep 16, 2003
Posts: 3
Hi,
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
x="Mother"
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)
Regards,
Sanju
 
Consider Paul's rocket mass heater.
 
subject: Wich is the different