Java OCA OCP Practice Question 1631

Question

What is the output of the following?

class Shape implements Comparable<Shape> {
   private String name;
   public Shape(String name) {
      this.name = name;
   }//from  w w  w  .j a v  a2s.  com
   @Override
   public int compareTo(Shape m) {
     return name.compareTo(m.name);
  }
  @Override
  public String toString() {
     return name;
  }
}
public class Newstand {
  public static void main(String[] args) {
     Set<Shape> set = new TreeSet<>();
     set.add(new Shape("A"));
     set.add(new Shape("B"));
     set.add(new Shape("A"));
     System.out.println(set.iterator().next());
  }
}
  • A. A
  • B. B
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


B.

Note

This code shows a proper implementation of Comparable.

It has the correct method signature.

It compares the magazine names in alphabetical order.

Remember that uppercase letters sort before lowercase letters.

Since B is uppercase, Option B is correct.




PreviousNext

Related