aspose file tools*
The moose likes Beginning Java and the fly likes if clause behaving strange 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 "if clause behaving strange" Watch "if clause behaving strange" New topic
Author

if clause behaving strange

Souvvik Basu
Ranch Hand

Joined: Apr 05, 2010
Posts: 96
Hi All,
I have a java class where I am using an if condition. The code for the class is :


When I run this, the output that I get is
1 ADMIN
2nd loop - role derived from DB is: ADMIN

Thus, it looks like = 1 and = ADMIN, still the if condition fails.

To understand this better, I did a few tests.
When I used , the test passed.
When I used , the test passed again.

Hence, the only time this doesnt seem to work, is when role is given the value of rs.getString(2) (which is odd...because in the sysout statement , the output clearly shows that the value of rs.getString(2) is indeed ADMIN

Can anyone please help me understand what is going wrong here?
Thanks in advance for your time and patience.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

The standard beginner error of using the == operator to compare the contents of two String objects. The == operator compares reference equality, i.e. it compares whether two references point at the same String. But it's possible for two different String objects to contain the same sequence of characters. If you want to test that (and you do want to test that), then use the equals() method:
Souvvik Basu
Ranch Hand

Joined: Apr 05, 2010
Posts: 96
Ahh!!! really stupid mistake
thanks Paul...... That was really helpful.
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

the real confusing part is that sometimes == works


SCJP
Visit my download page
Gihan Pandigamage
Ranch Hand

Joined: Aug 23, 2009
Posts: 60
The equals( ) method compares the characters inside the String object.
The == operator compares two object references to see whether they refer to the same instance.

above program prints "Equals".
according to the theory............
x.equals(y) returns ----> true
x==y returns ---->false
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38412
    
  23
Gihan Pandigamage wrote: . . . above program prints "Equals".
according to the theory............
x.equals(y) returns ----> true
x==y returns ---->false
Not at all. You have misread your if-else blocks.
 
Don't get me started about those stupid light bulbs.
 
subject: if clause behaving strange