This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wich is difference?

 
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
[ April 18, 2004: Message edited by: Ernest Friedman-Hill ]
 
Nathaniel Stoddard
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic