It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes byteRef.toString() == byteRef.toString() ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "byteRef.toString() == byteRef.toString() ?" Watch "byteRef.toString() == byteRef.toString() ?" New topic
Author

byteRef.toString() == byteRef.toString() ?

srilatha kareddy
Ranch Hand

Joined: Jan 12, 2006
Posts: 32
Byte b1 = new Byte("9");
if(b1.toString()==b1.toString())
System.out.println("true = "+(b1.hashCode()));
else
System.out.println("false = "+(b1.hashCode()));

o/p is true 9

Byte b1 = new Byte("11");
if(b1.toString()==b1.toString())
System.out.println("true = "+(b1.hashCode()));
else
System.out.println("false = "+(b1.hashCode()));

o/p is false 11


Please explain this
[ February 17, 2006: Message edited by: s reddy ]
steven gerrard
Ranch Hand

Joined: Jan 21, 2006
Posts: 55
i just compiled it its coming false in both the cases
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18133
    
  39

It depends on the JVM. Up to JDK 1.4, values from "-3" to "10" was cached -- meaning it will return the same string reference for same values, in this range. After JDK 1.4, it will return a new string everytime. (BTW, not exactly sure when it switched over)

Regardless, this is more reason to use equals() to compare strings.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
srilatha kareddy
Ranch Hand

Joined: Jan 12, 2006
Posts: 32
thanks for reply.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: byteRef.toString() == byteRef.toString() ?
 
Similar Threads
toString()
* Byte == comparision
Why is " == " on different strings with same content is returning "false"
Byte to string
toString( ) method