• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

if clause behaving strange

 
Souvvik Basu
Ranch Hand
Posts: 96
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 96
Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahh!!! really stupid mistake
thanks Paul...... That was really helpful.
 
Randall Twede
Ranch Hand
Posts: 4469
3
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the real confusing part is that sometimes == works
 
Gihan Pandigamage
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic