Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to compare?

 
Paulo Aquino
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm confused. I hope you can help me....when should i use the method equals() and when should i use the == operator?
 
Drake Silver
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
.equals() is when comparing strings.
Like say,
var
total = 10;
then
if(textFeild.getText().equals("10"))
do something...
or
if(string1.equals(string2))
do something...
equals() is used on strings.
 
Drake Silver
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
since java is case sensitive, it makes sense to test for multiple varitations of an input.
ex:
prompt: Enter Yes to continue.
User input may be:
yes, or Yes, or YES...or a few other ways.
Instead of testing for each different variation, you can use equalsIgnoreCase().
So:
prompt: Enter yes to continue.
if(textfield.getText().equalsIgnoreCase(string))
do something...
Just thought I'd add that, since up until recently I didn't know about it.
 
Jose Velarde
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simply put, you use == (1)for testing for equality of value of primitives, or (2)for testing whether two object references point to the same location in memory. On the other hand, the equals() method applies whatever test for equality the programmer provides.
For instance, in java.lang.String, equals() tests whether two String objects have the same content. However, in java.lang.Object, equals() actually is the same as == for objects.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic