Java OCA OCP Practice Question 2533

Question

Consider the following program and predict the output:

import java.util.HashSet;

class Shape{
     public Shape(int r) {
             rollNo = r;/*ww w .  java  2s  .  c  om*/
     }
     int rollNo;
 }

public class Main {
     public  static void main(String[] args){
             HashSet<Shape> students = new HashSet<>();
             students.add(new Shape(5));
             students.add(new Shape(10));
             System.out.println(students.contains(new Shape(10)));
     }
 }
  • a) This program prints the following: true.
  • b) This program prints the following: false.
  • c) This program results in a compiler error.
  • d) This program throws NoSuchElementException.


b)

Note

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




PreviousNext

Related