File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes == and String objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "== and String objects" Watch "== and String objects" New topic
Author

== and String objects

Gary Peck
Greenhorn

Joined: Jun 03, 2003
Posts: 15

PRINTS: False....this makes sense...two different objects

PRINTS: True ... makes sense because since there was no 'new' keyword the java pool uses the one already created

The question is: Why does this print False?
[ November 05, 2003: Message edited by: Gary Peck ]
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11252
    
  16

this is a guess, but i assume when you call b1.toString(), it makes a temporary String object in memory. when you call it again, it makes ANOTHER temporary String object.
they are different objects, so they are not == equal.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
It depends on what class b1 is and whether that class provides any guarantees about what its String method does. But in general, there are no guarantees about whether toString() will create a new String or reuse an existing one. You could look at the source code for b1's class to find out exactly what happens in this case, but usually this is just not very important. It's generally best to write code to se equals() rather than == when comparing Strings, and that way you won't be fooled by strange behavior like this.


"I'm not back." - Bill Harding, Twister
Gary Peck
Greenhorn

Joined: Jun 03, 2003
Posts: 15
Sorry.... b1 is the following:
Byte b1 = new Byte("127")
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: == and String objects