What is the difference between if(c==cmdLogin) and if(c.equals(cmdLogin))?Code:public void commandAction(Command c, Displayable d) { //if(c==cmdLogin) if(c.equals(cmdLogin))
Which one should be used and Why?
What is the difference between if(c==cmdLogin) and if(c.equals(cmdLogin))?Code:public void commandAction(Command c, Displayable d) { //if(c==cmdLogin) if(c.equals(cmdLogin))
Which one should be used and Why?
Hi komomo,
AFAI
The better way isIt will check the object reference ID , It is simpler.if(c==cmdLogin)
If you use theIt will Compare all the values which are there in the command class against to the other command class , I feel it is expensive , This is up to my understanding , If any one knows more about it please let know.if(c.equals(cmdLogin))
This is a very fundamental aspect of Java (and most other pointer-based languages) that you need to understand. In your example both "c" and "cmdLogin" are pointers -- addresses of objects in the heap. When you say "c==cmdLogin" you're asking if the two pointers point to the EXACT SAME object. In many cases this is what you want. But if the objects in question are, for instance, Strings, then you may have two different Strings that both contain the value "ABC", but their addresses will be different (since every object has a unique address). So for that case "c==cmdLogin" will be false, even though both Strings contain "ABC" (and thus "c.equals(cmdLogin)" will be true).
So the question you always have to ask is: Do I want to know if the two references are to the SAME OBJECT, or do I want to know if the two references reference the SAME VALUE? There's no single answer to this question, but it depends on the intent of your code.
Once you've mastered this concept you can bone up on "interned strings", for extra credit.