🧩 Part 2 — Nested Record Patterns (Java 21) Nested Record Patterns — The Next Step in Cleaner Java Last week, I showed how Java 21 lets you unpack records directly inside an if or switch. This week, let’s go a level deeper — nested record patterns. Suppose we have: public record Point(int x, int y) {} public record Rectangle(Point topLeft, Point bottomRight) {} Before (manual unpacking): if (shape instanceof Rectangle rect) { Point tl = rect.topLeft(); Point br = rect.bottomRight(); System.out.println("Top left: " + tl.x() + "," + tl.y()); } After (nested pattern): if (shape instanceof Rectangle(Point(int x1, int y1), Point(int x2, int y2))) { System.out.println("Top left: " + x1 + "," + y1); System.out.println("Bottom right: " + x2 + "," + y2); } You can destructure both levels in one clean statement — no casts, no temp variables, and still fully type-safe. It’s one of those features that feels small but reads like modern Java should. 👉 What’s your take — elegant or too much magic? #Java #Java21 #Records #PatternMatching #CleanCode #SoftwareEngineering
Nested Record Patterns in Java 21: Cleaner Code
More Relevant Posts
-
Java 21: Record Patterns Make Code Cleaner Than Ever I’ve been using records for DTOs and value objects for a while now. They cut out a ton of boilerplate — but in Java 21, records got even better. You can now deconstruct a record directly in an if statement or switch expression. Before (manual unpacking): if (obj instanceof Point) { Point p = (Point) obj; int x = p.x(); int y = p.y(); System.out.println("x=" + x + ", y=" + y); } After (record pattern): if (obj instanceof Point(int x, int y)) { System.out.println("x=" + x + ", y=" + y); } No casts, no extra variables — just clean, direct access to the data. Why I like it: ✅ Fewer lines and fewer mistakes ✅ Great for pattern-based logic and DTOs ✅ Works beautifully with switch expressions Small change, big clarity. 👉 Have you tried record patterns yet? #Java #Java21 #Records #CleanCode #SoftwareEngineering #Refactoring
To view or add a comment, sign in
-
🌳 Trees in Java — From Layman to Pro (2025 Edition) Ever wondered how hierarchical structures like file systems, JSON, or company org charts are represented in code? That’s where Trees come in — nature’s most elegant data structure 🌱 In my latest article, I break down Trees from scratch — starting with simple Java examples to architect-level insights: What makes a Tree different from linear structures Building and traversing a Binary Search Tree (BST) Understanding metrics like height, depth, diameter, balance factor, and leaf count How Trees relate to real-world systems (Kubernetes, APIs, ML models, databases) And yes, a complete working Java program you can run today 🚀 If you’ve ever felt Trees were confusing — this one will make them crystal clear. Simple visuals, intuitive explanations, and modern Java code (2025-ready). 👉 Read here: https://lnkd.in/dhsQQj2p #Java #DataStructures #SystemDesign #Coding #Learning #SoftwareEngineering #Algorithms #TechEducation
To view or add a comment, sign in
-
💡 Did you know that Sequenced Collections were introduced in Java 21 to solve the lack of a unified API for ordered collections? Before Java 21, many collections were already "sequenced" (such as: List, LinkedHashSet, LinkedHashMap, TreeSet, TreeMap) However, they didn't share a common interface that reflected this property. This led to inconsistent APIs. For example: • To get the first element of a List, you'd use list.get(0), but there was no equivalent for an ordered Set or Map. • To get the last element of a List, you'd use list.get(list.size() - 1), while for a LinkedHashSet, you'd have to iterate through the entire set. • To reverse a list you could use Collections.reverse(list), but for a LinkedHashSet or TreeMap, you’d need to copy elements into another structure. 🔧 Sequenced Collections fix this by introducing new interfaces: 🔹 SequencedCollection<E>: The main interface, which extends Collection<E>. It represents any collection with a defined order. 🔹SequencedSet<E>: Extends SequencedCollection<E> and Set<E>. Implemented by classes like LinkedHashSet. 🔹SequencedMap<K, V>: Extends Map<K, V>. Implemented by classes like LinkedHashMap. Existing classes like List, Deque, LinkedHashSet, and LinkedHashMap have been retrofitted to implement these new interfaces. 🔑 Key Methods The interface SequencedCollection provides a standard set of methods for accessing elements at either end: • getFirst(): Gets the first element • getLast(): Gets the last element • addFirst(E): Adds an element to the beginning. • addLast(E): Adds an element to the end. • removeFirst(): Removes and returns the first element. • removeLast(): Removes and returns the last element. • reversed(): This is a key feature. It returns a reverse-ordered view of the collection. #Java #Java21 #SequencedCollections #SoftwareDevelopment #LearningJava
To view or add a comment, sign in
-
-
💭 Java Memory Leaks: They Exist (Even with Garbage Collection!) 🧠 Most developers believe: > “Java has Garbage Collection, so memory leaks can’t happen.” But here’s the truth 👇 Even with GC, your app can still leak memory — and the scary part? It happens silently. 😬 --- ⚙️ How It Happens GC only removes objects that are no longer referenced. If something still holds a reference — even accidentally — the GC leaves it untouched. Common leak culprits 👇 1️⃣ Static fields — A static list or map that keeps growing and never cleared. 2️⃣ Inner classes / Anonymous classes — Hold an implicit reference to the outer class. 3️⃣ ThreadLocal misuse — Forgetting to call remove() keeps data alive across threads. 4️⃣ Caches that never expire — Especially when using custom in-memory maps. --- 🚨 Real-world example private static List<Data> cache = new ArrayList<>(); public void loadData() { cache.add(new Data()); } Every call keeps adding objects — and since cache is static, the GC can never reclaim that memory 🧱 --- 💡 How to Prevent It ✅ Always clear ThreadLocal after use ✅ Use WeakReference or WeakHashMap for caches ✅ Monitor heap usage with tools like VisualVM or Eclipse MAT ✅ Watch out for static collections or lingering listeners --- ⚡ The Takeaway Garbage Collection isn’t a silver bullet — it’s a helper, not a housekeeper. As engineers, it’s our job to manage references wisely 💪 --- 💬 Your turn: Have you ever faced a production memory issue that GC alone couldn’t fix? 👇 Share your experience — it might help someone else today! #Java #GarbageCollection #MemoryLeak #PerformanceTuning #BackendDevelopment #CleanCode #JavaDeveloper
To view or add a comment, sign in
-
(Union of Two Sorted Arrays — Java ) Hey everyone 👋 Today I implemented a program to find the Union of Two Sorted Arrays — while maintaining ascending order and avoiding duplicates. It looks simple at first, but the real challenge is handling duplicates efficiently and merging arrays in one traversal ⚙️ Here’s how I approached it 👇 💡 Concept: When two arrays are sorted, we can use two-pointer technique to compare elements and build the union in sorted order — without using any extra sorting later. ⚙️ Approach: 1️⃣ Initialize two pointers i and j for both arrays. 2️⃣ Compare arr1[i] and arr2[j]. • If one is smaller, add it to the union (if not duplicate). • If both are equal, add once and move both pointers. 3️⃣ Continue until both arrays are traversed. 4️⃣ Handle remaining elements in either array (checking for duplicates). 🧩 Key Takeaway: → Using two-pointer technique avoids extra sorting and reduces redundant comparisons. → Time Complexity: O(N + M) → Space Complexity: O(N + M) (for result storage) This problem helped me understand how small pointer-based optimizations can make merging logic both clean and efficient 🚀 Code is available on my GitHub repo: https://lnkd.in/eT335xuc #Java #DSA #Arrays #ProblemSolving #CodingJourney #TwoPointerTechnique #LearningByDoing #FullStackDeveloper #MCA
To view or add a comment, sign in
-
💭 Heap vs Stack Memory in Java — The Real Difference (Explained Simply) 🧠 You’ve probably heard these terms a hundred times: > “Object is stored in the heap.” “Local variable goes on the stack.” But what does that really mean? 🤔 Let’s break it down 👇 --- 🔹 1️⃣ Stack — The Short-Term Memory The stack stores: Method calls 🧩 Local variables References to objects in the heap It’s fast, organized in LIFO (Last-In, First-Out) order, and automatically cleared when a method ends. Once a method returns, all its stack frames vanish — poof 💨 Example 👇 void test() { int x = 10; // stored in stack String s = "Java"; // reference in stack, object in heap } --- 🔹 2️⃣ Heap — The Long-Term Memory The heap is where all objects live 🏠 It’s shared across threads and managed by the Garbage Collector. It’s slower than the stack — but it’s what makes Java flexible and object-oriented. When you do: Person p = new Person("Tushar"); → p (the reference) lives on the stack, → the actual Person object lives in the heap. --- ⚡ Pro Tip Memory leaks usually happen in the heap, while StackOverflowError (yes, the real one 😅) comes from — you guessed it — an overfilled stack due to deep recursion or infinite method calls. --- 💬 Your Turn Do you monitor heap and stack usage in your apps (via tools like VisualVM or JConsole)? 👇 Or do you just “trust the JVM”? #Java #MemoryManagement #JVM #GarbageCollection #BackendDevelopment #CleanCode #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
Java memory-mapped I/O in practice: patterns, pitfalls, and takeaways 📊 Java memory-mapped files offer near-zero-copy I/O by letting the OS page data in and out while you read and write through a mapped buffer backed by a FileChannel. Choose MapMode.READ_ONLY for static data and MapMode.READ_WRITE for writable regions, and map in chunks to fit your address space. 💡 Practical patterns Map large files in smaller regions to reduce page faults and address-space pressure. Use separate mappings for different regions rather than one huge map. Call force() after writes when durability across processes matters. ⚡ Pitfalls and tips Explicitly unmap when done to release resources and enable deletions. Be mindful of visibility; updates may require force() to reach storage. Buffers are not thread-safe; coordinate access across threads. 🚀 Takeaways Memory-mapped I/O shines for random, high-throughput access to large files, but it adds lifecycle and latency considerations. Pair it with sizing discipline and timely flushing to avoid resource leaks. What patterns have you found most effective for memory-mapped I/O in production—chunking, unmapping, or something else? What's your take? #Java #MemoryMappedIO #JavaNIO #Performance
To view or add a comment, sign in
-
💫 Difference Between String Literal and String Object In Java, Strings can be created in two ways — as a Literal or as an Object. Though both store text, they differ in memory allocation and creation process. Let’s understand how👇 ✨ 1️⃣ String Literal Created without using the new keyword. Stored in the String Constant Pool (SCP). Reuses memory if the same value already exists. ⚙️ 2️⃣ String Object Created explicitly using the new keyword. Stored in the heap memory (outside the SCP). Always creates a new object, even if the value is the same. 💡 In Short "Cindrella" → Literal → Stored in SCP, memory-efficient. new String("Cindrella") → Object → Stored in Heap, separate instance. #Java #StringConcepts #ObjectvsLiteral #CodingBasics #LearningJourney
To view or add a comment, sign in
-
-
💭 Ever wondered why your Java string operations feel slow sometimes? String vs StringBuilder vs StringBuffer — same syntax, different game. 1️⃣ STRING – Immutable & Simple Once created → it can’t be changed. Every modification creates a new object. Example: String s = "Java"; s = s + " Rocks!"; 👉 Two objects created — one discarded. ✅ Best for fixed text (like constants, messages, config values) ⚠️ Avoid in loops or repeated concatenations — it’s memory heavy 🔍 Why immutable? Thread-safe Used in String Pool for performance Prevents accidental modification 2️⃣ STRINGBUILDER – Mutable & Fast Edits the same object instead of creating new ones. Perfect for building large strings efficiently. Example: StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); ✅ Fast & memory-efficient ✅ Ideal for loops and dynamic string operations ⚠️ Not thread-safe — avoid in multi-threaded code 3️⃣ STRINGBUFFER – Mutable & Thread-Safe Same as StringBuilder but synchronized. That means only one thread can modify it at a time. Example: StringBuffer sb = new StringBuffer("Sync"); sb.append(" Safe"); ✅ Safe for multi-threaded applications ⚠️ Slower than StringBuilder due to synchronization
To view or add a comment, sign in
-
Java 21: String Templates — Finally, Clean String Interpolation For years, Java made us glue strings together with + or use String.format(). It worked, but it always looked messy: Before: String msg = "Hello " + name + "! You have " + count + " new messages."; Then came String.format() — a little cleaner, still clunky: String msg = String.format("Hello %s! You have %d new messages.", name, count); In Java 21 (preview), we finally get String Templates: String msg = STR."Hello, \{name}! You have \{count} new messages."; ✅ No more %s placeholders ✅ No concatenation clutter ✅ Works perfectly with text blocks for SQL, HTML, and JSON It feels natural, readable, and modern — the way strings should have worked all along. You’ll need to enable the preview flag to try it (--enable-preview), but once you do, it’s hard to go back. 👉 What do you think — does this make String.format() obsolete? #Java #Java21 #StringTemplates #CleanCode #SoftwareEngineering #Refactoring
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