Search code examples
javabluej

(Java) Comparing values of two variables in if-statement but can't use `.equals()`


(Heads up, I've never written a proper program before so bear with me)

I'm trying to write an if-statement that compares the VALUES of the position fields of two instances (which literally returns the integer "position"). Problem is, they are private fields in different classes so I cannot access them directly. Instead, I made methods in each class which return the variable.

Now in my if-statement, this is the condition that is to be true/false:

if (enemy1.getPosition() = player.getGun1Position())

Now the problem is, if I use = the machine assumes I'm trying to assign a value to the position of enemy1 and I've been researching to find that == compares the memory location rather than the value of the two fields.

I have also read that

.equals()

can be used but I'm assuming it can't be used here because

enemy1.getPosition().equals(player.getGun1Position())

gives an error when I try it.

NOTE: I cannot change the fields to public because this is for an assignment and the fields need to be private.

Any help would be appreciated :)


Solution

  • I'll briefly walk you through comparisons.

    1) Primitives just need == operator to match values except, String values which are not permitives will compare their memory locations. for strings use .equals().

    2) For objects of primitives like Integer,Double still compares the memory location with == operator. You need to invoke their .equals to compare them. If you have your own class you need to define your own version of equals method, means overriding.