This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ==,  why is it so ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "==,  why is it so ?" Watch "==,  why is it so ?" New topic

==, why is it so ?

Rajeev Ravindran
Ranch Hand

Joined: Aug 27, 2002
Posts: 455
hi all,
pls check this code
Byte b = new Byte("122");
String str = b.toString();
if(str == str)
System.out.println("str = " + str); // 1
if(b.toString() == b.toString())
System.out.println("==" );
System.out.println("not ==" ); // 2
// 1 and // 2 are getting printed..could anyone tell me the reason ??

SCJP, SCWCD, SCBCD, Oracle Certified Professional (SQL n PL/SQL)
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Because an == comparison only works with Strings when they are in the String pool, not when they are created on the heap. the toString() method creates Strings on the heap. You need to do this:

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Kem Bro

Joined: Oct 17, 2001
Posts: 25
Hi Raj,
As you're dealing with Strings you should use the .equals(String s) method that the String class overrides from Object. This evaluates the String value.
Using == on the Strings returned returns false because they are different String objects, even though their hashCode() may be the same.
Check out this code:
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println( s1.hashCode() );
System.out.println( s2.hashCode() );
System.out.println( s3.hashCode() );
System.out.println( s1==s2 ); // s1 and s2 refer to the same object in the String pool
System.out.println( s1==s3 ); // s1 and s3 refer to different objects, new String created
System.out.println( s1.equals(s2) ); // compares value
System.out.println( s1.equals(s3) ); // compares value
[/ CODE]

Rajeev Ravindran
Ranch Hand

Joined: Aug 27, 2002
Posts: 455
thanks Thomas
thanks Kem
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
Welcome to Javaranch
We'd like you to read the Javaranch Naming Policy and change your publicly displayed name (change it here) to comply with our unique rule. Thank you.
PS: Quote from the naming policy:

For your publicly displayed name, use a first name, a space, and a last name. Obviously fictitious names or improperly formatted names may be locked out.

[Blog] [Blogroll] [My Reviews] My Linked In
I agree. Here's the link:
subject: ==, why is it so ?
It's not a secret anymore!