🚀 𝐋𝐋𝐃 #𝟑: 𝐒𝐢𝐧𝐠𝐥𝐞𝐭𝐨𝐧 𝐃𝐞𝐬𝐢𝐠𝐧 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 Ever wondered how to ensure only one instance of a class exists in your application? I’ve explained the Singleton Pattern in the easiest way — covering all implementations with simple Java examples 👇 💡 You’ll learn: Lazy vs Eager initialization Thread-safe approaches Double-checked locking Best practices like Bill Pugh & Enum Singleton 👉 This is one of the most asked patterns in backend & system design interviews Perfect for: ✔️ Java developers ✔️ Backend engineers ✔️ Interview preparation 📌 Check out the full article here: https://lnkd.in/giawgixN #LLD #Java #DesignPatterns #Backend #SoftwareEngineering #SystemDesign
Singleton Pattern in Java: Lazy & Eager Initialization
More Relevant Posts
-
🔀 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝙞𝙣 𝙅𝙖𝙫𝙖 Why does it happen? This is one exception many developers face while working with collections 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧? ➡️ It occurs when we modify a collection while iterating over it 📃 Example 𝐢𝐦𝐩𝐨𝐫𝐭 𝐣𝐚𝐯𝐚.𝐮𝐭𝐢𝐥.*; 𝐩𝐮𝐛𝐥𝐢𝐜 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐋𝐢𝐬𝐭<𝐈𝐧𝐭𝐞𝐠𝐞𝐫> 𝐥𝐢𝐬𝐭 = 𝐧𝐞𝐰 𝐀𝐫𝐫𝐚𝐲𝐋𝐢𝐬𝐭<>(); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟏); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟐); 𝐥𝐢𝐬𝐭.𝐚𝐝𝐝(𝟑); 𝐟𝐨𝐫 (𝐈𝐧𝐭𝐞𝐠𝐞𝐫 𝐢 : 𝐥𝐢𝐬𝐭) { 𝐢𝐟 (𝐢 == 𝟐) { 𝐥𝐢𝐬𝐭.𝐫𝐞𝐦𝐨𝐯𝐞(𝐢); // 𝐜𝐚𝐮𝐬𝐞𝐬 𝐞𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 } } } } ⚠️ 𝐖𝐡𝐲 𝐝𝐨𝐞𝐬 𝐭𝐡𝐢𝐬 𝐡𝐚𝐩𝐩𝐞𝐧? Internally, Java collections use an Iterator When we modify the collection directly: ❌ Structure changes ❌ Iterator gets confused Throws ➡️ 𝐂𝐨𝐧𝐜𝐮𝐫𝐫𝐞𝐧𝐭𝐌𝐨𝐝𝐢𝐟𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 Ways to Fix ➡️ Use Iterator 𝐈𝐭𝐞𝐫𝐚𝐭𝐨𝐫<𝐈𝐧𝐭𝐞𝐠𝐞𝐫> 𝐢𝐭 = 𝐥𝐢𝐬𝐭.𝐢𝐭𝐞𝐫𝐚𝐭𝐨𝐫(); 𝐰𝐡𝐢𝐥𝐞 (𝐢𝐭.𝐡𝐚𝐬𝐍𝐞𝐱𝐭()) { 𝐢𝐟 (𝐢𝐭.𝐧𝐞𝐱𝐭() == 𝟐) { 𝐢𝐭.𝐫𝐞𝐦𝐨𝐯𝐞(); // 𝐬𝐚𝐟𝐞 } } ➡️ Use removeIf() (Java 8) list.removeIf(i -> i == 2); ▪️Always avoid modifying a collection directly during iteration ▪️Use safe methods provided by Java (use iterator) Have you ever faced this exception in your project? 🤔 How did you fix it? #Java #JavaDeveloper #JavaBackend #Programming #TechJourney #LearnBySharing #JavaConcepts #Collections #InterviewPrep #Developers
To view or add a comment, sign in
-
🚀 Do you really know the order in which Java executes your code? Most developers write code… But fewer truly understand how Java executes it behind the scenes. Let’s break one of the most asked (and misunderstood) concepts 👇 🧠 Java Execution Order (Class → Object) Whenever a class is used and an object is created, Java follows this strict order: 👉 Step 1: Static Phase (Runs only once) - Static variables - Static blocks ➡ Executed top to bottom 👉 Step 2: Instance Phase (Runs every time you create an object) - Instance variables - Instance blocks ➡ Executed top to bottom 👉 Step 3: Constructor - Finally, the constructor is executed --- 🔥 Final Order (Must Remember) ✔ Static Variables ✔ Static Blocks ✔ Instance Variables ✔ Instance Blocks ✔ Constructor --- 🧩 Example class Demo { static int a = print("Static A"); static { print("Static Block"); } int x = print("Instance X"); { print("Instance Block"); } Demo() { print("Constructor"); } static int print(String msg) { System.out.println(msg); return 0; } public static void main(String[] args) { new Demo(); } } 💡 Output: Static A Static Block Instance X Instance Block Constructor --- ⚠️ Pro Tips 🔹 Static runs only once per class 🔹 Instance logic runs for every object 🔹 In inheritance: - Parent → Child (Static) - Parent → Constructor → Child (Instance) --- 🎯 Why this matters? Understanding this helps you: ✔ Debug tricky initialization issues ✔ Write predictable code ✔ Perform better in interviews --- 💬 Next time you write a class, ask yourself: “What runs first?” #Java #JavaInternals #Programming #Developers #CodingInterview #TechLearning
To view or add a comment, sign in
-
-
𝐃𝐞𝐬𝐢𝐠𝐧 𝐚 𝐒𝐜𝐚𝐥𝐚𝐛𝐥𝐞 𝐑𝐚𝐭𝐞 𝐋𝐢𝐦𝐢𝐭𝐞𝐫 𝐢𝐧 𝐉𝐚𝐯𝐚 𝐰𝐢𝐭𝐡 𝐑𝐮𝐧𝐭𝐢𝐦𝐞 𝐂𝐨𝐧𝐟𝐢𝐠𝐮𝐫𝐚𝐭𝐢𝐨𝐧 𝐔𝐩𝐝𝐚𝐭𝐞𝐬 This was the question I was asked in an 𝐢𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰. I couldn’t answer it 𝐨𝐩𝐭𝐢𝐦𝐚𝐥𝐥𝐲 back then. So I went back, studied it properly, and implemented it again — this time the right way. Now I’ve built it using different approaches like Token Bucket and Sliding Window, along with production-level considerations like thread safety and runtime configuration updates. If you’re preparing for backend or system design interviews, this is a must-know topic. 👉 Visit this post for the full implementation and explanation. https://lnkd.in/gW929rdz #SystemDesign #BackendDevelopment #Java #SoftwareEngineering #InterviewPreparation #Microservices #Scalability #Learning #Tech
To view or add a comment, sign in
-
🚀 Singleton Design Pattern in Java – With Complete Code & Explanation Today I solved a HackerRank challenge on the Singleton Pattern — a very important concept in object-oriented design. 🎯 What is Singleton? 👉 Ensures that a class has only one instance and provides a global access point to it. 🛠️ Complete Code with Line-by-Line Explanation: import java.util.Scanner; import java.lang.reflect.*; // Singleton class class Singleton { // Step 1: Create a single static instance of the class public static final Singleton singleton = new Singleton(); // Step 2: Public variable to store string public String str; // Step 3: Private constructor (prevents object creation from outside) private Singleton() { } // Step 4: Public method to return the single instance public static Singleton getSingleInstance() { return singleton; } } // Main class public class Main { public static void main(String args[]) throws Exception { // Scanner to take input Scanner sc = new Scanner(System.in); // Step 5: Get the same instance twice Singleton s1 = Singleton.getSingleInstance(); // first reference Singleton s2 = Singleton.getSingleInstance(); // second reference // Step 6: Check both references point to same object assert (s1 == s2); // true means Singleton works // Step 7: Verify constructor is private using Reflection Class c = s1.getClass(); Constructor[] allConstructors = c.getDeclaredConstructors(); assert allConstructors.length == 1; for (Constructor ctor : allConstructors) { // Modifier 2 = private if (ctor.getModifiers() != 2 || !ctor.toString().equals("private Singleton()")) { System.out.println("Wrong class!"); } } // Step 8: Take input string String str = sc.nextLine(); // Step 9: Assign value to singleton object s1.str = str; s2.str = str; // both refer to same object // Step 10: Print output System.out.println("Hello I am a singleton! Let me say " + str + " to you"); } } 💡 Key Takeaways: ✔ Only one object is created ✔ Constructor is private ✔ Access through static method ✔ Memory efficient & widely used 🔥 Where is it used? 👉 Logging systems 👉 Configuration management 👉 Database connections #Java #DesignPatterns #SingletonPattern #OOP #HackerRank #CodingPractice #JavaDeveloper #LearningJourney
To view or add a comment, sign in
-
⚡ map vs flatMap in Java (Stream API) Definition: map() → Transforms each element 1:1 flatMap() → Transforms and flattens nested structures 🤔 Why use? 1. map() - When output is a single value per input - Simple transformations 2. flatMap() - When each element produces multiple values (collections/streams) - Avoid nested structures like List<List<T>> 💻 Example List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5, 6) ); // map() → creates nested structure List<Stream<Integer>> mapResult = list.stream() .map(inner -> inner.stream()) .collect(Collectors.toList()); // flatMap() → flattens into single stream List<Integer> flatMapResult = list.stream() .flatMap(inner -> inner.stream()) .collect(Collectors.toList()); 🔄 Flow map() List<List> → Stream<List> → Stream<Stream> flatMap() List<List> → Stream<List> → Stream 🧠 Rule of Thumb 👉 If your transformation returns a single value → use map() 👉 If it returns a collection/stream → use flatMap() 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Backend #Streams #Java8 #CodingInterview #InterviewPrep #SoftwareEngineering
To view or add a comment, sign in
-
-
🌟 Hello Shining Stars!!! 🙏 💡 Java Type Promotion Hierarchy (Must-Know for Developers) Understanding type promotion is key to avoiding subtle bugs in Java 👇 🔼 Hierarchy (Widening Conversion): byte → short → int → long → float → double char → int → long → float → double ⚡ Golden Rules: 👉 byte, short, and char are automatically promoted to int in expressions 👉 Result = largest data type in the expression 👉 ✅ Promotion (widening) is automatic 👉 ❌ De-promotion (narrowing) is NOT automatic — requires explicit casting 🚨 Edge Case Examples (Tricky but Important): byte a = 10; byte b = 20; byte c = a + b; // ❌ Compilation Error // a + b becomes int → cannot store in byte without casting int x = 130; byte b = (byte) x; // ⚠️ Explicit cast (data loss) // Output will be -126 due to overflow char ch = 'A'; System.out.println(ch + 1); // Output: 66 // 'A' → 65 → promoted to int 🧠 Method vs Constructor Promotion (Important Interview Point): void test(int x) { System.out.println("int method"); } void test(double x) { System.out.println("double method"); } test(10); // Calls int method (exact match preferred over promotion) 👉 In methods, Java allows type promotion during overload resolution 👉 But constructors don’t “prefer” promotion the same way — exact match is prioritized, and ambiguous cases can lead to compilation errors 🎯 Takeaway: Java silently promotes smaller types, but it never automatically demotes them — and overload resolution can surprise you! #Java #Programming #Developers #Coding #InterviewPrep #TechTips 👍 Like | 🔁 Repost | 🔄 Share | 💬 Comment | 🔔 Follow | 🤝 Connect to grow together
To view or add a comment, sign in
-
👉 Constructor = Object initialization + No Inheritance + No Static 🔁 Initialization Order in Java: ->Static variables & static blocks (once / class) ->Instance variables (default → explicit) ->Instance initializer blocks (once / object ) Constructor ⚡ Interview-Ready Facts (No fluff) Can a constructor be static? ❌ No Constructor belongs to object not class Can a constructor be private?-✅ Yes → Used in Singleton, Utility classes Can a constructor be final?❌ No → No inheritance → No overriding → No need Can a constructor be abstract? ❌ No 👉 Abstract = No implementation 👉 Constructor = Must initialize object Can we override a constructor? ❌ No → Not inherited Can we overload a constructor? ✅ Yes Can we call constructor explicitly? ✅ Yes → this() or super() Can constructor return value?❌ No Constructor inside constructor? ✅ Yes → Constructor chaining this() → same class super() → parent class Can constructor throw exception? ✅ Yes Can we call constructor from a method? ❌ No → Only via new A(). 💡 Final Thought Constructor questions are rarely about syntax. They test your understanding of: Object lifecycle Inheritance behavior JVM initialization flow #Java #SDET #InterviewPrep #OOP #BackendDevelopment
To view or add a comment, sign in
-
🔹 Singleton Design Pattern in Java — A Practical Overview The Singleton pattern is one of the most fundamental design patterns in Java, widely used in real-world applications for managing shared resources. 🔹 What is Singleton? The Singleton pattern ensures: • Only one instance of a class is created • A global access point is provided to that instance 🔹 Common Use Cases • Database connection management • Logging frameworks • Application configuration • Caching mechanisms 🔹 Basic Implementation (Lazy Initialization) public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } 🔹 Limitation This implementation is not thread-safe. In a multi-threaded environment, multiple instances may be created. 🔹 Thread-Safe Implementation public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } 🔹 Recommended Approach Bill Pugh Singleton (Inner Static Class) public class Singleton { private Singleton() {} private static class Holder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return Holder.INSTANCE; } } Advantages: • Thread-safe without synchronization overhead • Lazy initialization • Clean and maintainable implementation 🔹 Alternative (Robust Approach) public enum Singleton { INSTANCE; } Advantages: • Inherently thread-safe • Handles serialization • Prevents reflection-based instantiation 🔹 Key Takeaways • Prefer Bill Pugh Singleton for most scenarios • Use Enum Singleton for maximum robustness • Always consider thread-safety in concurrent applications #Java #DesignPatterns #BackendDevelopment #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
💻 Exception Handling in Java — Write Robust Code 🚀 Handling errors properly is what separates basic code from production-ready applications. This visual breaks down Exception Handling in Java in a simple yet technical way 👇 🧠 What is an Exception? An exception is an unexpected event that occurs during program execution and disrupts the normal flow. 👉 Example: Division by zero → ArithmeticException 🔍 Exception Hierarchy: Object ↳ Throwable ↳ Error (System-level, not recoverable) ↳ Exception (Can be handled) ✔ Checked Exceptions (Compile-time) ✔ Unchecked Exceptions (Runtime) ⚡ Types of Exceptions: ✔ Checked → Must be handled (IOException, SQLException) ✔ Unchecked → Runtime errors (NullPointerException, ArrayIndexOutOfBoundsException) 🔄 Try-Catch-Finally Flow: 1️⃣ try → Code that may cause exception 2️⃣ catch → Handle the exception 3️⃣ finally → Always executes (cleanup resources) 🛠 Throw vs Throws: throw → Explicitly throw an exception throws → Declare exceptions in method signature 🧪 Custom Exceptions: Create your own exceptions for business logic validation → improves readability & control ⚠️ Common Exceptions: ArithmeticException NullPointerException ArrayIndexOutOfBoundsException IOException 🔥 Best Practices: ✔ Handle specific exceptions (avoid generic catch) ✔ Use meaningful error messages ✔ Always release resources (finally / try-with-resources) ✔ Don’t ignore exceptions silently ✔ Use custom exceptions where needed 🎯 Key takeaway: Exception handling is not just about avoiding crashes — it’s about building reliable, maintainable, and user-friendly applications. #Java #ExceptionHandling #Programming #SoftwareEngineering #BackendDevelopment #Coding #Learning
To view or add a comment, sign in
-
-
Java 17+ Interview Question 🔥 | Sealed Interfaces Explained Imagine you have a Payment interface implemented by UPIPayment and CardPayment. Everything is fine until another developer adds a CashPayment class that also implements it — but your client doesn’t want that. How do you restrict which classes can implement the Payment interface? Before Java 17, there was no clean way to enforce this. Solution: Use the sealed keyword (introduced in Java 17) with the permits clause. ————————— sealed interface Payment permits UPIPayment, CardPayment { } final class UPIPayment implements Payment { } final class CardPayment implements Payment { } // This will now give a compilation error // class CashPayment implements Payment { } —————————- Key Rules: • Only the classes listed in permits can implement the sealed interface. • Every implementing class must be explicitly marked as: • final → cannot be extended further • sealed → can define its own permitted subclasses • non-sealed → can be freely extended You can also combine this with records (which are implicitly final). This feature gives you full control over the inheritance hierarchy at compile time — no more unexpected implementations in large codebases. What would you choose for UPIPayment — final, sealed, or non-sealed? And why does a record work without explicitly adding final? Drop your thoughts in the comments 👇 #Java #Java17 #SealedInterfaces #JavaInterviewQuestions #BackendDevelopment #ProgrammingTips #AI #ML
To view or add a comment, sign in
-
Explore related topics
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