Problem category: Logic Problems
Diagnosis Difficulty: Easy-Medium
Difficulty to Fix: Easy-Medium
A common problem among many beginning (and some not so beginning) programmers is the incorrect use of the equal operator and equals() method.
The equals operator is used exclusively to compare the value of primitives, or to compare the references (memory addresses) of objects.
// proper usage of the == operator int a = 5; int b = 5; if(a == b) // test if the value a equals the value b { System.out.println("a and b have the same value"); }
The equals() method is used to define when two object values are equal. They do not necessarily have to be the same object (though, if they are they should return true for equals() as well as ==).
public Class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } /** * Two points are equal if they have the same x and y value */ public boolean equals(Point o) { if(o == null) { return false; } return o.x == x && o.y == y; } public static void main(String[] args) { Point p1 = new Point(4,5); Point p2 = new Point(4,5); // p2 is a physically in a different location in memory, but it contains the same value as p1 if(p1.equals(p2)) { System.out.println("p1 and p2 have the same value"); } if(p1 == p2) { System.out.println("p1 and p2 are the same object in memory"); } } }
Suggested fixes
You must determine which behavior you want in your particular instance. Sometimes you do want to compare two objects to see if they are the exact same object. However, in the majority of cases you will want to use the equals() method when comparing two objects.