Warning Common mistake is to use the == operator to test class types for equality.
Note: Using == for class types will not generate a compile error, but it is WRONG! Using == just compares the addresses, not the values of class objects.
Example: basic types
Use == to test for equality for basic types.
1 public static void main(String[] args) 2 { 3 Scanner in = new Scanner(System.in); 4 int x, y; 5 6 x = in.nextInt(); 7 y = in.nextInt(); 8 9 if (x == y) { 10 System.out.printf("equal"); 11 } else { 12 System.out.printf("not equal"); 13 } 14 }
Example: class types
Use the equals method to test for equality for class types.
1 public static void main(String[] args) 2 { 3 Scanner in = new Scanner(System.in); 4 String x, y; 5 6 x = in.next(); 7 y = in.next(); 8 9 if (x.equals(y)) { 10 System.out.printf("equal"); 11 } else { 12 System.out.printf("not equal"); 13 } 14 }