Java OCA OCP Practice Question 3031

Question

Given the class definition:

class Student{
       public Student(int r) {
               rollNo = r;
       }
       int rollNo;
}

Choose the correct option based on this code segment:

HashSet<Student> students = new HashSet<>();
students.add(new Student(5));
students.add(new Student(10));
System.out.println(students.contains(new Student(10)));
  • a) this program prints the following: true
  • b) this program prints the following: false
  • c) this program results in compiler error(s)
  • d) this program throws NoSuchElementException


b)

Note

Since methods equals() and hashcode() methods are not overridden in the Student class, the contains() method will not work as intended and prints false.




PreviousNext

Related