[Logo]
Forums Register Login
Wich is the different
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
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
That feels good. Thanks. Here's a tiny ad:
Thread Boost - a very different sort of advertising
https://coderanch.com/t/674455/Thread-Boost-feature


This thread has been viewed 568 times.

All times above are in ranch (not your local) time.
The current ranch time is
Apr 22, 2018 14:24:55.