This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wich is the different

 
Carlos rodriguez
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic