Java Questions and Answers


What are Anonymous Classes in Java?


  • Anonymous class is an expression
  • Declare and instantiate a class at the same time
  • Do not have name
  • It consists of new operator
  • Could implement interface or extend class
  • Because it is an expression, statement should end with semicolon


interface Print {
    public void display();

// Anonymous class
Print search = new Print() {
    String name = "Waheguru";
    public void display() {
        System.out.println("Oneness " + name);


What is difference between Java Comparator and Comparable?


  • Both interfaces are available to define custom sorting
  • Class need to implement interface and override method
  • Both are Functional Interfaces. Meaning lambda expression can be provided to have different type of sorting in different situations
  • Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.


int compare(T o1, T o2)
  • Compares its two arguments for order


int compareTo(T o)
  • Object comparing itself with another object


Leave a Reply

Your email address will not be published. Required fields are marked *