Post 06 Effective Java – Item 6 Avoid Creating Unnecessary Objects As Java developers, we often focus on writing correct code, but writing efficient code is just as important. 💡 Core idea: Don’t create objects if you can reuse them. Why does this matter? Object creation is expensive Unnecessary objects increase GC pressure Impacts performance and memory Simple examples 👇 ❌ Bad String s = new String("hello"); ✅ Good String s = "hello"; Another one: ❌ Bad Boolean flag = new Boolean(true); ✅ Good Boolean flag = Boolean.TRUE; Key takeaways: ✔ Prefer immutable objects ✔ Reuse objects instead of recreating them ✔ Be cautious with objects inside loops ✔ Use static factory methods when possible Small optimizations like this, when applied consistently, separate average code from production-grade code. source - Effective Java ~ joshua bloch #EffectiveJava #Java #CleanCode #Performance #SoftwareEngineering #BackendDevelopment #LearningInPublic
Optimize Java Code with Immutable Objects
More Relevant Posts
-
📘 Core Java Day 20 | Why Interfaces Have Private Methods & How Java Solves the Diamond Problem With Java 8, interfaces changed significantly, Why Interfaces Have Private Methods? - Private methods in interfaces are used as helper methods. - They support default methods - They avoid code duplication inside interfaces - They cannot be accessed or overridden by implementing classes How Java Solves the Diamond Problem in Interfaces? Interfaces can extend multiple interfaces, which can lead to method conflicts when default methods are involved. Java solves this by: - Forcing the implementing class to override the conflicting method - Making the decision explicit instead of automatic Because: - Interfaces don’t have constructors - No state is inherited (static final) - Ambiguity is resolved at compile time
To view or add a comment, sign in
-
-
📌 Multiple Catch Blocks in Java — Why Order Matters In Java, when handling multiple exceptions, the order of catch blocks is not just a style choice — it is a language rule. ❌ Incorrect Order (Compile-time Error) try { // risky code } catch (Exception e) { // generic exception handling } catch (NullPointerException e) { // compile-time error } This code does not compile. Reason: • Exception is the parent class • NullPointerException is a child class • The child exception becomes unreachable Java prevents this at compile time to avoid ambiguous exception handling. ✅ Correct Order try { // risky code } catch (NullPointerException e) { // specific handling } catch (Exception e) { // generic handling } In this case: • Specific exceptions are handled first • Generic exceptions act as a fallback 🧠 Important Rule Always catch exceptions from: • Most specific → Most generic 💡 Why This Rule Exists • Ensures precise exception handling • Prevents unreachable code • Improves readability and maintainability Understanding exception hierarchy helps write safer and cleaner Java code. #Java #CoreJava #ExceptionHandling #Programming #BackendDevelopment
To view or add a comment, sign in
-
I used to overuse Optional in Java. Then I learned when not to use it. Optional is great for: • Return types • Avoiding null checks • Making intent clear But using it everywhere can actually make code worse. ❌ Don’t do this: class User { Optional<String> email; } Why? • Makes serialization messy • Complicates getters/setters • Adds noise where it’s not needed ✅ Better approach: Optional<String> findEmailByUserId(Long userId); Rule of thumb I follow now: 👉 Use Optional at the boundaries, not inside your models. Java gives us powerful tools, but knowing where to use them matters more than just knowing how. Clean code is less about showing knowledge and more about reducing confusion. What’s one Java feature you stopped overusing after some experience? #Java #CleanCode #BackendDevelopment #SoftwareEngineering #LearningInPublic #OptionalInJava #Optimization
To view or add a comment, sign in
-
Hello Java Developers, 🚀 Day 13 – Java Revision Series Today’s topic covers a lesser-known but very important enhancement introduced in Java 9. ❓ Question Why do interfaces support private and private static methods in Java? ✅ Answer Before Java 9, interfaces could have: abstract methods default methods static methods But there was no way to share common logic internally inside an interface. To solve this problem, Java 9 introduced: private methods private static methods inside interfaces. 🔹 Why Were Private Methods Introduced in Interfaces? Default methods often contain duplicate logic. Without private methods: Code duplication increased Interfaces became harder to maintain Private methods allow: Code reuse inside the interface Cleaner and more maintainable default methods Better encapsulation 🔹 Private Method in Interface A private method: Can be used by default methods Can be used by other private methods Cannot be accessed outside the interface Cannot be overridden by implementing classes 📌 Used for instance-level shared logic. 🔹 Private Static Method in Interface A private static method: Is shared across all implementations Can be called only from: default methods static methods inside the interface Does not depend on object state 📌 Used for utility/helper logic. #Java #CoreJava #NestedClasses #StaticKeyword #OOP #JavaDeveloper #LearningInPublic #InterviewPreparation
To view or add a comment, sign in
-
-
🔖 Marker Interface in Java — Explained Simply Not all interfaces define behavior. Some exist only to signal capability — these are called Marker Interfaces. ⸻ ✅ What is a Marker Interface? A Marker Interface is an interface with no methods. It marks a class so the JVM or framework changes behavior at runtime. Example: Serializable, Cloneable ⸻ 🆚 Marker vs Normal Interface Normal Interface • Defines what a class should do • Has methods • Compile-time contract 👉 Example: Runnable Marker Interface • Defines what a class is allowed to do • No methods • Runtime check 👉 Example: Serializable ⸻ 🤔 Why Marker Interfaces? ✔ Enable / restrict features ✔ Control JVM behavior ✔ Avoid forcing unnecessary methods ⸻ 📌 Common Examples • Serializable → Allows object serialization • Cloneable → Allows object cloning • RandomAccess → Optimizes list access ⸻ 💡 Key Insight Marker Interfaces use metadata instead of methods to control behavior. ⸻ 🚀 Final Thought In Java, sometimes doing nothing enables everything. ⸻ #Java #CoreJava #MarkerInterface #JavaInterview #BackendDeveloper #SpringBoot
To view or add a comment, sign in
-
Why Java doesn’t support multiple inheritance ? Here’s the answer: Java avoids multiple inheritance with classes to prevent ambiguity and complexity, especially the Diamond Problem, where a class can’t decide which parent’s method to inherit. What’s Diamond problem? The Diamond Problem 💎 If Class C inherits from Class A and Class B, and both override the same method, Java wouldn’t know which implementation to use. This leads to unpredictable behavior. Java’s smart alternative ✅ Java allows multiple inheritance through interfaces: • Interfaces define behavior, not state • Default methods must be explicitly resolved if there’s a conflict • Keeps code flexible and safe Java chose clarity over complexity — no multiple inheritance of classes, but powerful interfaces instead.
To view or add a comment, sign in
-
-
🚀✨ What is the Diamond Problem in Java? 👩🎓The Diamond Problem occurs when a child class implements two or more interfaces that contain the same default method. This creates confusion for the child class: Which interface’s default method should be called? ⚠️ Example Scenario 🔹Interface A → default method show() 🔹Interface B → default method show() 🔹Class C implements A, B ➡️ Java doesn’t know whether to use A.show() or B.show(). ✅ Solution To resolve this ambiguity: The child class must override the default method and provide its own implementation. 📌 Important Notes ✔ Java does NOT support multiple inheritance using classes ✔ Since Java 8, interfaces can have default methods ✔ Diamond Problem exists only with interfaces, not classes ✔ Overriding the method removes ambiguity 🎯 Key Takeaway Java avoids multiple inheritance with classes to keep the language simple, clear, and less error-prone, while allowing flexibility through interfaces. 💡 Understanding such core concepts helps you write better, cleaner Java code. #Java #OOPs #Java8 #Interfaces #DiamondProblem #Parmeshwarmetkar #SoftwareEngineering #LearnJava
To view or add a comment, sign in
-
-
🔹 Immutability in Java – Building Safer and Reliable Code 🔹 Immutability means once an object is created, its state cannot be changed. In Java, immutable objects help in writing secure, thread-safe, and predictable applications. ✅ Key Characteristics of Immutable Objects State cannot be modified after creation No setter methods Fields are declared final Class is often declared final Changes result in new object creation ✅ Why Immutability Matters ✔ Thread-safe by design ✔ Improves security ✔ Simplifies debugging ✔ Prevents accidental changes “Immutable objects are easy to reason about and hard to break.” 📌 Common Example String class in Java is immutable Any modification creates a new String object instead of changing the existing one. ✨ Immutability is a powerful concept for writing robust and concurrent Java applications. #Java #Immutability #CoreJava #OOPConcepts #JavaDeveloper #SoftwareEngineering
To view or add a comment, sign in
-
-
🔐 Immutability in Java: From Classic Design to Records Designing an immutable class in Java means ensuring the object’s state never changes after creation. 🛠️ Traditional immutability rules: 🔒 Make the class final 🧱 Fields should be private final 🧩 Initialize state only via constructor 🚫 No setters 🛡️ Defensive copies for mutable objects (List, Map, Date) 📈 Result: Thread-safe by design ⚙️ Predictable behavior 🔍 Easier maintenance 🧠 👉 Now enter Java Records 🚀 Java records provide native support for immutability, enabling developers to: ✂️ Write less boilerplate code ♻️ Reduce code repetition 📖 Improve readability 🧪 Make code easy to test and reason about public record Employee(String name, int age) {} 🧠 One line replaces: Fields Constructor Getters equals(), hashCode(), toString() 🎯 Best use cases: DTOs 📦 API contracts 🌐 Value objects 🧩 Event models 📣 ⚠️ Architect’s note: Records are shallowly immutable. If they hold mutable objects, defensive copying is still required 🔍 💡 Punchline Immutability was once a discipline. Records make it the default. #Java #Immutability #JavaRecords #CleanCode #SystemDesign #SolutionArchitecture #BackendEngineering 💻🔥
To view or add a comment, sign in
Explore related topics
- Simple Ways To Improve Code Quality
- How to Improve Code Maintainability and Avoid Spaghetti Code
- How to Achieve Clean Code Structure
- Coding Best Practices to Reduce Developer Mistakes
- Code Planning Tips for Entry-Level Developers
- Ways to Improve Coding Logic for Free
- Keeping Code DRY: Don't Repeat Yourself
- Best Practices for Writing Clean Code
- How Developers Use Composition in Programming
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
Informative