aspose file tools*
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Wich is difference?" Watch "Wich is difference?" New topic
Author

Wich is difference?

Carlos rodriguez
Greenhorn

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;
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

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


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Wich is difference?