BhauAutomation

Checked vs Unchecked Exceptions & Comparable vs Comparator

Learn key Java interview concepts with clear examples and differences between Checked vs Unchecked Exceptions and Comparable vs Comparator interfaces.

Checked vs Unchecked Exceptions

In Java, exceptions are categorized into Checked and Unchecked based on compile-time checking. Understanding this difference is important for writing robust programs.

Checked Exceptions

Checked exceptions are checked at compile-time. You must handle them using try-catch blocks or declare them using throws in the method signature. Examples include IOException, SQLException, and FileNotFoundException.

Unchecked Exceptions

Unchecked exceptions are checked at runtime only. There is no requirement to handle them explicitly. Examples include NullPointerException, ArithmeticException, and ArrayIndexOutOfBoundsException.

Difference Table

Basis Checked Exception Unchecked Exception
Checking Compile-time Runtime
Handling Must handle with try-catch or throws Not mandatory to handle
Examples IOException, SQLException NullPointerException, ArithmeticException
Package java.io, java.sql java.lang

Example:

Checked Exception:

try {
   FileReader fr = new FileReader("file.txt");
} catch (IOException e) {
   e.printStackTrace();
}
    

Unchecked Exception:

int x = 10 / 0; // Throws ArithmeticException at runtime
    

Comparable vs Comparator

Both Comparable and Comparator are interfaces used to compare objects in Java, but they differ in how and where they define comparison logic.

Comparable Interface

The Comparable interface belongs to java.lang package and defines the natural ordering of objects. The class itself implements compareTo() method to determine order.

Comparator Interface

The Comparator interface belongs to java.util package and is used for custom ordering externally. You implement compare() method without modifying the original class.

Difference Table

Basis Comparable Comparator
Package java.lang java.util
Method compareTo(Object o) compare(Object o1, Object o2)
Sorting Logic Inside the same class In a separate class
Number of Sort Orders Only one natural order Multiple custom orders possible
Example Collections.sort(list) Collections.sort(list, comparator)

Example:

Comparable Example:

class Student implements Comparable<Student> {
   int rollno;
   String name;
   public int compareTo(Student s) {
      return this.rollno - s.rollno;
   }
}
    

Comparator Example:

Comparator<Student> nameComparator = (s1, s2) ->
   s1.name.compareTo(s2.name);
Collections.sort(list, nameComparator);