File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== and String objects

 
Gary Peck
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Pie
Posts: 12015
24
Chrome Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gary Peck
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry.... b1 is the following:
Byte b1 = new Byte("127")
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic