• Post Reply Bookmark Topic Watch Topic
  • New Topic

when I print values of 2 variables they are the same but my if statement does not see them a(SOLVED)  RSS feed

 
Matt Kohanek
Village Idiot
Ranch Hand
Posts: 484
Java jQuery Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do various operations to fill in variables in different classes, and now I need an if statement that checks to see if a variable from one class is equal to a variable from another class.

Here is the simple java code I made to test it:



So first it prints out the deviceId and channelId being tested in the first output and then the if statement tests if they match. If they do it prints out "Successful Match", if not it prints out "No Match"

When I run this here is the output:

Testing channelDeviceId against projectDeviceId: exampleDevice1 and exampleDevice1
No Match

So in the first output line it is obvious that the value are equal - exampleDevice1 and exampleDevice1.

So why is it that when evaluated by the if statement it sees those as not being equal and goes to the else statement and prints out "No Match"?

Ive been having trouble like this with other things for a while but have just worked around it but it is really becoming a bother. Is there just something wrong with my if statement() ?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Testing channelDeviceId against projectDeviceId: exampleDevice1 and exampleDevice1
No Match


That is because two different things are going in. In the case of the println(), the toString() method of the object is called -- which can be overriden to return the same value even though it is different objects. In the case of the if statement, you are doing a reference comparison, which is true only if it is the same object.

Instead of checking to see if the objects are the same object, you need to check to see if the object have the same value.

Now, if you have overridden the equals() method correctly, this can be done like so...



If the equals() method have not been overridden, but you want the if statement to be true if the println() returns the same string value, then you can also...



Henry
 
Matt Kohanek
Village Idiot
Ranch Hand
Posts: 484
Java jQuery Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much sir, I cant believe I forgot that from my beginner java class. Thanks a lot.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!