Java OCA OCP Practice Question 2538

Question

What is the result of the following code?

1:    public class Employee { 
2:       public int employeeId; 
3:       public String firstName, lastName; 
4:       public int yearStarted; 
5:       @Override public int hashCode() { 
6:          return employeeId; 
7:       } //from ww  w . j  a v  a2s  .  c o  m
8:       public boolean equals(Employee e) { 
9:          return this.employeeId == e.employeeId; 
10:      } 
11:      public static void main(String[] args) { 
12:         Employee one = new Employee(); 
13:         one.employeeId = 101; 
14:         Employee two = new Employee(); 
15:         two.employeeId = 101; 
16:         if (one.equals(two)) System.out.println("Success"); 
17:         else System.out.println("Failure"); 
18:     } } 
  • A. Success
  • B. Failure
  • C. The hashCode() method fails to compile.
  • D. The equals() method fails to compile.
  • E. Another line of code fails to compile.
  • F. A runtime exception is thrown.


A.

Note

Based on the equals() method in the code, objects are equal if they have the same employeeId.

The hashCode() method correctly overrides the one from Object.

The equals() method is an overload of the one from Object and not an override.

It would be better to pass Object since an override would be better to use here.

It is odd to override hashCode() and not equals().




PreviousNext

Related