Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • 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 difference?  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
[ April 18, 2004: Message edited by: Ernest Friedman-Hill ]
 
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carlos,
you should post these "basic" issues on the beginners forum so others can benefit from the discussion. It has to do with how Java handles literal strings. Literal strings are kept in what we call the "literal string pool". In such a way, you could evaluate x == y and it will be true (first case).
In the second case, you are using the "new" keyword, which explicitly creates a new object on the heap. In that case you are actually creating three strings. One (the literal) is placed in the "literal string pool". The other two are created on the heap and just refer to the literal one. At that point, x == y will evaluate false, while x.equals(y) will of course equal true.
 
author and iconoclast
Sheriff
Posts: 24220
40
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java in General (Beginner). Any followups there, please. I also took the graemlin out of the subject line -- they don't work there.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!