One Java concept that helped me better understand sorting and comparing objects is Comparator & Comparable. In Java, both Comparable and Comparator are used to define how objects should be sorted. Comparable allows a class to define its default sorting logic using the "compareTo()" method. Comparator, on the other hand, lets us create custom sorting rules using the "compare()" method, which is useful when we want to sort objects in different ways. While exploring backend development, I noticed this concept is useful when sorting collections of objects such as employees, products, or students based on attributes like name, price, or ID. It helps organise data clearly and makes applications more flexible. This topic also appears frequently in Java interviews, because it checks whether developers understand object comparison, sorting collections, and writing cleaner, reusable logic. For me, learning the difference between "Comparable and Comparator" made working with collections much easier and more practical. 🧠 When sorting objects in Java projects, do you usually prefer using Comparable or Comparator, and why? 🙂 #Java #CoreJava #JavaCollections #Comparator #Comparable #BackendDevelopment #JavaDeveloper #DeveloperLearning
Java Sorting: Comparable vs Comparator
More Relevant Posts
-
🚀 Comparable in Java — Why & When to Use It? Sorting objects in Java becomes simple when you understand Comparable. Let’s break it down 👇 🔹 What is Comparable? Comparable is used to define the natural (default) sorting order of objects within a class. 🔹 Why Use Comparable? ✔ To define a default sorting logic inside the class ✔ Makes sorting easy using "Collections.sort()" or "Arrays.sort()" ✔ Avoids writing external sorting logic again and again 🔹 When to Use Comparable? ✔ When objects have a natural order (like ID, age, name) ✔ When sorting is required frequently ✔ When you want a single standard sorting rule 🔹 Steps to Implement Comparable 1️⃣ Implement "Comparable<T>" in your class 2️⃣ Override "compareTo()" method 3️⃣ Define comparison logic (this vs other object) 4️⃣ Use "Collections.sort()" to sort objects 💡 Key Insight: «Comparable = Natural sorting (inside the class)» 🔥 Mastering this makes your code cleaner and interview-ready #Java #CoreJava #Comparable #Sorting #Collections #Programming #CodingInterview #Developers #SoftwareDevelopment #LearnJava 🚀
To view or add a comment, sign in
-
-
Java Concept Check — Answer Explained 💡 Yesterday I posted a question: Which combination of Java keywords cannot be used together while declaring a class? Options were: A) public static B) final abstract C) public final D) abstract class ✅ Correct Answer: B) final abstract Why? In Java: 🔹 abstract class - Cannot be instantiated (no direct object creation) - Must be extended by another class Example: abstract class A { } 🔹 final class - Cannot be extended by any other class - Object creation is allowed Example: final class B { } The contradiction If we combine them: final abstract class A { } We create a conflict: - "abstract" → class must be inherited - "final" → class cannot be inherited Because these two rules contradict each other, Java does not allow this combination, resulting in a compile-time error. Thanks to everyone who participated in the poll 👇 Did you get the correct answer? #Java #BackendDevelopment #JavaDeveloper #Programming
To view or add a comment, sign in
-
Java is quietly becoming more expressive This is not the Java you learned 5 years ago. Modern Java (21 → 25) is becoming much more concise and safer. 🧠 Old Java if (obj instanceof User) { User user = (User) obj; return user.getName(); } else if (obj instanceof Admin) { Admin admin = (Admin) obj; return admin.getRole(); } 👉 verbose 👉 error-prone 👉 easy to forget cases 🚀 Modern Java return switch (obj) { case User user -> user.getName(); case Admin admin -> admin.getRole(); default -> throw new IllegalStateException(); }; ⚡ Even better with sealed classes Java sealed interface Account permits User, Admin {} 👉 Now the compiler knows all possible types 👉 and forces you to handle them 💥 Why this matters less boilerplate safer code (exhaustive checks) fewer runtime bugs 👉 the compiler does more work for you ⚠️ What I still see in real projects old instanceof patterns manual casting everywhere missing edge cases 🧠 Takeaway Modern Java is not just about performance. It’s about writing safer and cleaner code. 🔍 Bonus Once your code is clean, the next challenge is making it efficient. That’s what I focus on with: 👉 https://joptimize.io Are you still writing Java 8-style code in 2025? #JavaDev #Java25 #Java21 #CleanCode #Backend #SoftwareEngineering
To view or add a comment, sign in
-
🚀🎊Day 84 of 90 – Java Backend Development ✨🎆 In Java, the final keyword is a non-access modifier used to restrict the user from changing the state of a variable, method, or class. Think of it as a way to achieve immutability and prevent inheritance or overriding. 👉 1. Final variables: When you declare a variable as final, its value cannot be modified once it has been initialized. It essentially becomes a constant. i) Local Variables: Must be initialized before use and cannot be reassigned. ii) Instance Variables: Can be initialized during declaration or inside the constructor. iii) Static Variables: Often used to create "Class Constants" (e.g., public static final double PI = 3.14159;). Note: For objects, final means the reference cannot change. You can still modify the internal state (fields) of the object, but you cannot point the variable to a new object. 👉2. Final methods: A method declared with the final keyword cannot be overridden by subclasses. i) Usage: Use this when you want to ensure that the specific implementation of a method remains consistent across all subclasses. ii) Performance: Historically, the compiler could optimize final methods through inlining, though modern JVMs often do this automatically regardless. 👉 3. Final classes: A class declared as final cannot be subclassed (inherited). i) Security & Integrity: Many standard Java library classes are final, such as String, Integer, and other wrapper classes. This prevents developers from creating a "fake" version of a String that might behave maliciously. ii) Implicitly Final: If a class is final, all of its methods are implicitly final as well. 👉 Code example: final class Vehicle { // Cannot be inherited final int SPEED_LIMIT = 90; // Constant final void drive() { // Cannot be overridden System.out.println("Driving at " + SPEED_LIMIT); } } #FinalKeyword #Immutable #Performance #Java #Constant
To view or add a comment, sign in
-
-
🚀 Understanding Method Overloading in Java 🔥 Let's break down the concept of method overloading in Java! Method overloading allows developers to define multiple methods with the same name but different parameters, making code more flexible and readable. This means you can have multiple methods with the same name, as long as the parameters differ in type or number. ⚡️ Why does method overloading matter for developers? It helps streamline code by promoting code reusability and enhancing readability. By using method overloading, developers can create cleaner code that is easier to maintain and understand. 👨💻 Here's a step-by-step breakdown: 1️⃣ Create multiple methods with the same name 2️⃣ Ensure the parameters are different in either type or number 3️⃣ The Java compiler determines which method to execute based on the arguments provided 📝 Full code example: ``` public class Calculate { public int sum(int a, int b) { return a + b; } public double sum(double a, double b) { return a + b; } } ``` 💡 Pro tip: Avoid overloading methods with the same number and type of parameters, as it can lead to ambiguity. ⚠️ Common mistake: Forgetting that the return type of the overloaded methods can be the same. ❓ How do you use method overloading in your Java projects? Do you have any favorite tricks? Share below! 💬 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JavaProgramming #MethodOverloading #CodeFlexibility #LearnToCode #DeveloperTips #CleanCode #JavaDev #CodingCommunity #TechTalks
To view or add a comment, sign in
-
-
Q. Can an Interface Extend a Class in Java? This is a common confusion among developers and even I revisited this concept deeply today. - The answer is NO, an interface cannot extend a class. - It can only extend another interface. But there is something interesting: - Even though an interface doesn’t extend Object, all public methods of the Object class are implicitly available inside every interface. Methods like: • toString() • hashCode() • equals() These are treated as abstractly redeclared in every interface. ⚡ Why does Java do this? - To support upcasting and polymorphism, ensuring that any object referenced via an interface can still access these fundamental methods. ❗ Important Rule: While you can declare these methods in an interface, you cannot provide default implementations for them. interface Alpha { default String toString() { // ❌ Compile time error return "Hello"; } } Reason? Because these methods already have implementations in the Object class. Since every class implicitly extends Object, allowing default implementations of these methods in interfaces would create ambiguity during method resolution. Therefore, Java does not allow interfaces to provide default implementations for Object methods. 📌 Interfaces don’t extend Object, but its public methods are implicitly available. However, default implementations for them are not allowed. #Java #OOP #InterviewPreparation #Programming #Developers #Learning #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Java Trap: Why "finally" Doesn’t Change the Returned Value 👇 👉 Primitive vs Object Behavior in "finally" 🤔 Looks tricky… but very important to understand. --- 👉 Example 1 (Primitive): public static int test() { int x = 10; try { return x; } finally { x = 20; } } 👉 Output: 10 😲 Why not 20? 💡 Java stores return value before executing "finally" - "x = 10" stored - "finally" runs → changes "x" to 20 - But already stored value (10) is returned --- 👉 Example 2 (Object): public static StringBuilder test() { StringBuilder sb = new StringBuilder("Hello"); try { return sb; } finally { sb.append(" World"); } } 👉 Output: Hello World 😲 Why changed here? 💡 Object reference is returned - Same object is modified in "finally" - So changes are visible --- 🔥 Rule to remember: - Primitive → value copied → no change - Object → reference returned → changes visible --- 💭 Subtle concept… very common interview question. #Java #Programming #Coding #Developers #JavaTips #InterviewPrep 🚀
To view or add a comment, sign in
-
Java Devs, let's talk about a core concept that makes our code cleaner and more flexible: "Method Overloading"! Ever wanted to perform similar operations with different inputs without creating a bunch of uniquely named methods? That's where Method Overloading shines! It's a fantastic example of compile-time polymorphism (aka static polymorphism or early binding) that allows a class to have multiple methods with the "same name", as long as their parameter lists are different. Key takeaways: * Same method name, different parameters = ✅ * Cannot overload by return type alone (parameters *must* differ) ⚠️ * The compiler is smart! It picks the most specific match. 🧠 Check out this quick example: ```java class Product { public int multiply(int a, int b) { // Multiplies two numbers return a * b; } public int multiply(int a, int b, int c) { // Multiplies three numbers return a * b * c; } } // Output: // Product of the two integer value: 2 // Product of the three integer value: 6 ``` See how elegant that is? One `multiply` method, multiple functionalities! What are your favorite use cases for Method Overloading in your Java projects? Share in the comments! 👇 #Java #JavaDevelopment #Programming #SoftwareDevelopment #BeginnerProgramming
To view or add a comment, sign in
-
-
In Java, Abstraction Can Either Save You — Or Confuse You At some point, every developer learns: 👉 “Use abstraction” 👉 “Write reusable code” So we start creating: • interfaces for everything • generic services • utility layers • shared modules But slowly, something changes. A simple flow becomes: Controller → Service → Helper → Util → CommonService → BaseService Now: ✔ nothing is duplicated ❌ but nothing is clear either Abstraction is powerful. But too much abstraction hides intent. Good Java design is not about maximum reuse. It’s about meaningful boundaries. If someone needs 5 files to understand one flow, the abstraction is not helping. Sometimes the best code is: ✔ a direct method ✔ in the right class ✔ with clear responsibility Not everything needs to be reusable. Some things just need to be understandable. What’s the most over-engineered abstraction you’ve seen in a Java project? #Java #CleanCode #SoftwareEngineering #BackendDevelopment #JavaDeveloper
To view or add a comment, sign in
-
How Garbage Collection actually works in Java ? Most developers know this much: “Java automatically deletes unused objects.” That’s true - but not how it actually works. Here’s what really happens: Java doesn’t delete objects randomly. It uses Garbage Collection (GC) to manage memory intelligently. Step 1: Object creation Objects are created in the Heap memory. Step 2: Reachability check Java checks if an object is still being used. If an object has no references pointing to it, it becomes eligible for garbage collection. Step 3: Mark and Sweep The JVM: • Marks all reachable (active) objects • Identifies unused ones • Removes those unused objects from memory Step 4: Memory cleanup Freed memory is reused for new objects. Here’s the key insight: Garbage Collection is not immediate. Just because an object has no reference doesn’t mean it’s deleted instantly. The JVM decides when to run GC based on memory needs. Java doesn’t magically manage memory. It uses smart algorithms to track object usage and clean up when needed. That’s what makes Java powerful - and sometimes unpredictable. #Java #JVM #GarbageCollection #CSFundamentals #BackendDevelopment
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development