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 == and String objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "== and String objects" Watch "== and String objects" New topic

== and String objects

Gary Peck

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

Joined: Oct 02, 2003
Posts: 11955

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

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

Joined: Jun 03, 2003
Posts: 15
Sorry.... b1 is the following:
Byte b1 = new Byte("127")
I agree. Here's the link:
subject: == and String objects
jQuery in Action, 3rd edition