File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Wich is difference? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Wich is difference?" Watch "Wich is difference?" New topic

Wich is difference?

Carlos rodriguez

Joined: Apr 14, 2004
Posts: 2
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;
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
Carlos A Rodriguez C
[ April 18, 2004: Message edited by: Ernest Friedman-Hill ]
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
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

Joined: Jul 08, 2003
Posts: 24195

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.

[Jess in Action][AskingGoodQuestions]
subject: Wich is difference?
It's not a secret anymore!