🔹 Introduction Sorting objects is a common requirement in Java, and interviewers often ask: 👉 “What is the difference between Comparator and Comparable?” 🔹 What is Comparable? Comparable is used to define natural sorting . 👉 It is implemented inside the class itself 🔹 Example (Comparable) import java . util . *; class Employee implements Comparable < Employee > { int salary ; Employee ( int salary ) { this . salary = salary ; } public int compareTo ( Employee e ) { return this . salary - e . salary ; } } public class Test { public static void main ( String [] args ) { List < Employee > list = Arrays . asList ( new Employee ( 50000 ), new Employee ( 30000 ), new Employee ( 70000 ) ); Collections . sort ( list ); list . forEach ( e -> System . out . println ( e . salary )); } } 🔹 What is Comparator? Comparator i...
Learn Java interview questions with simple explanations, code examples, and step-by-step solutions. Perfect for freshers and experienced developers preparing for technical interviews.