Java SE 8 Programmer II — Question 145

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.id = = b.id) {
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?

Answer options

Correct answer: B

Explanation

The correct answer is B because the equals method checks if the ids of the two Book objects are the same, and since b1.id is 101 and b2.id is 102, it returns false. Option A is incorrect as the output is false. Options C and D involve compilation errors that do not affect the execution outcome in this context.