Java SE 8 Programmer II Exam: Question from 1Z0-809

Java SE 8 Programmer II Exam: Question from 1Z0-809

Question

Given: class Book { int id; String name; public Book (int id, String name){ this.id = id; this.name = name; } public boolean equals (Object obj) {//line n1 boolean output = false; Book b = (Book) obj; if (this.name.equals(b name))} output = true; } return output; } } and the code fragment: Book b1 = new Book (101, "Java Programing"); Book b2 = new Book (102, "Java Programing"); System.out.println (b1.equals(b2));//line n2 Which statement is true?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The given code defines a class Book that has two instance variables id and name, and a constructor that initializes these variables. The class also overrides the equals method of the Object class to compare two Book objects based on the name variable.

In the code fragment, two Book objects, b1 and b2, are created with different id values but the same name value "Java Programming". Then the equals method of b1 is called with b2 as an argument, and the result is printed to the console.

Now let's analyze each answer option:

A. The program prints true.

This is not correct, as the equals method of Book compares the name variable of two objects, and b1 and b2 have different id values. Therefore, the equals method will return false, and the program will print false.

B. The program prints false.

This is the correct answer, as explained above.

C. A compilation error occurs. To ensure successful compilation, replace line n1 with: boolean equals (Book obj) {

This is not correct, as the equals method signature is already correct. The Object class defines the equals method as boolean equals(Object obj), and the Book class overrides it correctly with boolean equals(Object obj).

D. A compilation error occurs. To ensure successful compilation, replace line n2 with: System.out.println (b1.equals((Object) b2));

This is also not correct, as the method call b1.equals(b2) is already correct. The equals method takes an Object argument, and b2 is implicitly cast to Object when passed to the method. Therefore, the code fragment will compile and run without any errors.