• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Wich is the different  RSS feed

 
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
 
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!