If you compare references (Objects
) then use .equals()
, but if you compare primitive types (int
, float
, double
etc...) you should use ==
.
In your case it looks like you are comparing ints
, so you can use ==
without a problem.
( board.getBoardPositionValue(i, j) == coin.getCoinNumber()
)
Further: If you want to check if two Object
s are the same then you may use ==
, but if you wish to check their content you will want to use .equals()
. For example, checking if two Strings
are equal or not using the equality operator (==
) and not with .equals()
method is a mistake.
Check this out for a classic example of using .equals()
or ==
in String
:
String a = "abc";
String b = "abc";
// returns true because a and b points to same string object
if(a == b){
System.out.println("Strings are equal by == because they are cached in the string pool");
}
b = new String("abc");
// returns false as now b isn't a string literal and points to a different object
if(a == b){
System.out.println("String literal and String created with new() are equal using ==");
}else{
System.out.println("String literal and String created with new() are not equal using ==");
}
//both strings are equal because their content is the same
if(a.equals(b)){
System.out.println("Two Strings are equal in Java using the equals() method because their content is the same");
}else{
System.out.println("Two Strings are not equal in Java using the equals() method because their content is the same");
}