Dev Notes #05 Strings in Java don't change. They just pretend to. I was dry running a piece of code. Two strings. One lowercase, one upper. 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟷 = "𝚑𝚎𝚕𝚕𝚘"; 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟸 = "𝙷𝙴𝙻𝙻𝙾"; 𝚜𝟸.𝚝𝚘𝙻𝚘𝚠𝚎𝚛𝙲𝚊𝚜𝚎(); 𝚒𝚏 (𝚜𝟷 == 𝚜𝟸) // 𝚠𝚒𝚕𝚕 𝚝𝚑𝚒𝚜 𝚎𝚟𝚎𝚛 𝚋𝚎 𝚝𝚛𝚞𝚎? My first instinct, "Yeah they should match" That was my carelessness if anything, They didn't. And they never will. Here's what's actually happening: 𝚜𝟸.𝚝𝚘𝙻𝚘𝚠𝚎𝚛𝙲𝚊𝚜𝚎(); doesn't modify 𝚜𝟸. It creates a brand new String object and throws it away because nobody caught it. 𝚜𝟸 is still "𝙷𝙴𝙻𝙻𝙾", completely unbothered. The fix is as follows: 𝚜𝟸 = 𝚜𝟸.𝚝𝚘𝙻𝚘𝚠𝚎𝚛𝙲𝚊𝚜𝚎(); Strings are immutable. Every method you call on them returns a new object. The original never changes. Immutability makes Strings safe to share across threads, safe to use as HashMap keys, and predictable in behavior. And yes, one more thing, Even after the fix, 𝚜𝟷 == 𝚜𝟸 is still the wrong comparison. == checks if both variables point to the same object in memory. .𝚎𝚚𝚞𝚊𝚕𝚜() checks if they hold the same value. 𝚜𝟸 = 𝚜𝟸.𝚝𝚘𝙻𝚘𝚠𝚎𝚛𝙲𝚊𝚜𝚎(); 𝚜𝟷 == 𝚜𝟸 // 𝚏𝚊𝚕𝚜𝚎 (𝚍𝚒𝚏𝚏𝚎𝚛𝚎𝚗𝚝 𝚘𝚋𝚓𝚎𝚌𝚝𝚜) 𝚜𝟷.𝚎𝚚𝚞𝚊𝚕𝚜(𝚜𝟸) // 𝚝𝚛𝚞𝚎 (𝚜𝚊𝚖𝚎 𝚟𝚊𝚕𝚞𝚎) Two separate lessons hiding inside one silly mistake. Was truly a facepalm moment for me this time. Did such events ever happen to you? #Java #DevNotes #LearningInPublic #SpringBoot #BackendDevelopment
Arindam Pal’s Post
More Relevant Posts
-
💡 Strings in Java — Small Concept, Big Impact At first, I thought Strings were simple… But in real projects, I learned: ➡️ Strings are immutable ➡️ Memory is optimized using String Pool ➡️ Wrong usage can impact performance Example mistake I made: String result = ""; for (int i = 0; i < 1000; i++) { result += i; // ❌ creates multiple objects } ✅ Better approach: StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i); } ✨ What I learned: ✔ Use StringBuilder for heavy operations ✔ Understand equals() vs == ✔ Be mindful of memory Sometimes the simplest concepts teach the biggest lessons. #Java #Strings #CleanCode #SoftwareEngineering #BackendDevelopment #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day 3 – Why String is Immutable in Java (and why it matters) One question I explored today: Why are "String" objects immutable in Java? String s = "hello"; s.concat(" world"); System.out.println(s); // still "hello" 👉 Instead of modifying the existing object, Java creates a new String But why was it designed this way? ✔ Security – Strings are widely used in sensitive areas (like class loading, file paths, network connections). Immutability prevents accidental or malicious changes. ✔ Performance (String Pool) – Since Strings don’t change, they can be safely reused from the pool, saving memory. ✔ Thread Safety – No synchronization needed, multiple threads can use the same String safely. 💡 This also explains why classes like "StringBuilder" and "StringBuffer" exist—for mutable operations when performance matters. Small design decision, but huge impact on how Java applications behave internally. #Java #BackendDevelopment #JavaInternals #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
Something small… but it changed how I think about Java performance. We often assume `substring()` is cheap. Just a slice of the original string… right? That was true **once**. 👉 In older Java versions, `substring()` shared the same internal char array. Fast… but risky — a tiny substring could keep a huge string alive in memory. 👉 In modern Java, things changed. `substring()` now creates a **new String with its own memory**. Same value ❌ Same reference ❌ Safer memory ✅ And this is where the real learning hit me: **Understanding behavior > memorizing APIs** Because in a real system: * Frequent substring operations = more objects * More objects = more GC pressure * More GC = performance impact So the question is not: “Do I know substring?” But: “Do I know what it costs at runtime?” That shift — from syntax to system thinking — is where growth actually starts. #Java #BackendEngineering #Performance #JVM #LearningJourney
To view or add a comment, sign in
-
Hello Connections, Post 18 — Java Fundamentals A-Z This one makes your code 10x cleaner. Most developers avoid it. 😱 Can you spot the difference? 👇 // ❌ Before Java 8 — verbose and painful! List<String> names = Arrays.asList( "Charlie", "Alice", "Bob" ); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return a.compareTo(b); } }); 8 lines. Just to sort a list. 😬 // ✅ With Lambda — clean and powerful! Collections.sort(names, (a, b) -> a.compareTo(b)); // ✅ Done! // Even cleaner with method reference! names.sort(String::compareTo); // ✅ One liner! // Real example! transactions.stream() .filter(t -> t.getAmount() > 10000) // Lambda! .forEach(t -> System.out.println(t)); // Lambda! Lambda = anonymous function // Structure of a Lambda (parameters) -> expression // Examples () -> System.out.println("Hello") // No params (n) -> n * 2 // One param (a, b) -> a + b // Two params (a, b) -> { // Block body int sum = a + b; return sum; } Post 18 Summary: 🔴 Unlearned → Writing verbose anonymous classes for simple operations 🟢 Relearned → Lambda = concise anonymous function — write less do more! 🤯 Biggest surprise → Replaced 50 lines of transaction processing code with 5 lines using Lambdas! Have you started using Lambdas? Drop a λ below! #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2 Follow along for more! 👇
To view or add a comment, sign in
-
-
Java’s "Diamond Problem" evolved. Here is how you solve it. 💎⚔️ Think interfaces solved all our multiple inheritance problems? Not quite. Since Java 8, we’ve had Default Methods. They are great for backward compatibility, but they introduced a major headache:Method Collision. The Nightmare Scenario: You have two interfaces, Camera and Phone. Both have a default void start() method. Now, you create a SmartPhone class that implements both. Java looks at your code and asks: "Which 'start' should I run? The lens opening or the screen lighting up?" 🤔 Java’s Golden Rule: No Guessing Allowed. 🚫 The compiler won’t even let you run the code. It forces YOU to be the judge. 👨⚖️ How to "Pick a Winner" (The Syntax): You must override the conflicting method in your class. You can write new logic, or explicitly call the parent you prefer using the super keyword: @Override public void start() { Camera.super.start(); // This picks the Camera's version! } Why this matters: This is Java’s philosophy in action: Explicit is always better than Implicit. By forcing you to choose, Java eliminates the "hidden bugs" that plague languages like C++. It’s not just a restriction; it’s a safeguard for your architecture. 🛡️ Have you ever run into a default method conflict in a large project? How did you handle it? Let's discuss below! 👇 #Java #SoftwareEngineering #CodingTips #BackendDevelopment #CleanCode #Java8 #ProgrammingLogic #TechCommunity
To view or add a comment, sign in
-
Day 12 Today’s Java practice was about solving the Leader Element problem. Instead of using nested loops, I used a single traversal from right to left, which made the solution clean and efficient. A leader element is one that is greater than all the elements to its right. Example: Input: {16,17,5,3,4,2} Leaders: 17, 5, 4, 2 🧠 Approach I used: ->Start traversing from the rightmost element ->Keep track of the maximum element seen so far ->If the current element is greater than the maximum, it becomes a leader ->This is an efficient approach with O(n) time complexity and no extra space. ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online class Main { public static void main(String[] args) { int a [] ={16,17,5,3,4,2}; int length=a.length; int maxRight=a[length-1]; System.out.print("Leader elements are :"+maxRight+" "); for(int i=a[length-2];i>=0;i--) { if(a[i]>maxRight) { maxRight=a[i]; System.out.print(maxRight+" "); } } } } Output:Leader elements are :2 4 5 17 #AutomationTestEngineer #Selenium #Java #DeveloperJourney #Arrays
To view or add a comment, sign in
-
-
🚦 Thread Safety in Java - Why Your Code Breaks Under Concurrency Your code works perfectly with 1 user. But when multiple threads hit the same object together… chaos starts. Two threads may try to update the same data at the same time → causing race conditions, inconsistent values, and hard-to-debug production issues. 🔍 What is Thread Safety? A class or block of code is called thread-safe when it behaves correctly even when accessed by multiple threads simultaneously. Meaning: ✔ No corrupted data ✔ No unexpected outputs ✔ Predictable execution ⚠ Common Problem count++; Looks harmless, right? But internally it is: 1. Read count 2. Increment 3. Write back If two threads do this together, one update can be lost. ✅ How Java Handles Thread Safety 1. synchronized keyword Allows only one thread at a time inside critical section. public synchronized void increment() { count++; } 2. Atomic Classes For lightweight thread-safe operations. AtomicInteger count = new AtomicInteger(); count.incrementAndGet(); 3. Concurrent Collections Use thread-safe collections like: 1. ConcurrentHashMap 2. CopyOnWriteArrayList instead of normal HashMap/List in multithreaded apps. 4. Immutability Objects that never change are naturally thread-safe. 💡 Rule of Thumb If multiple threads share mutable data, protection is mandatory. Otherwise bugs won't appear in local testing... they appear directly in production 😄 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Multithreading #ThreadSafety #BackendDevelopment #SpringBoot #JavaDeveloper #Programming #InterviewPrep #Concurrency #SoftwareEngineering
To view or add a comment, sign in
-
-
Garbage Collection in Java – How JVM Cleans Memory 🧹 In C/C++, memory must be freed manually. In Java? The JVM handles it automatically using Garbage Collection. How it works: ▸ GC runs automatically inside the JVM ▸ Identifies objects with NO active references ▸ Removes them from Heap memory ▸ Frees space for new object allocation JVM Heap Structure: 1️⃣ Young Generation → New objects are created here → Minor GC runs frequently (fast cleanup) 2️⃣ Old Generation → Long-living objects move here → Major/Full GC runs here (slower & expensive) 3️⃣ Metaspace (Java 8+) → Stores class metadata → Replaced PermGen Can we force GC? ▸ "System.gc()" only suggests the JVM to run GC ▸ Execution is NOT guaranteed Behind the scenes: → JVM uses different GC algorithms like: ▸ Serial GC ▸ G1 GC (default in modern JVMs) ▸ ZGC / Shenandoah (low-latency collectors) Best Practices: → Avoid creating unnecessary objects → Don’t rely on "System.gc()" → Close resources using try-with-resources → Nullify references only when necessary (e.g., large unused objects) #Java #SpringBoot #GarbageCollection #JVM #JavaDeveloper #BackendDeveloper
To view or add a comment, sign in
-
-
8 Java Maps. 8 Different Problems. Which One Do You Actually Need? Most developers default to HashMap for everything. That's like using a hammer for every job in the toolbox. Here's the breakdown you didn't get in college: 1. HashMap → O(1) get/put, no ordering, not thread-safe. Use when: you just need fast key-value lookup. 2. LinkedHashMap → Maintains insertion order via doubly linked list. Use when: building LRU caches or ordered iteration matters. 3. TreeMap → Sorted keys, O(log n), backed by Red-Black tree. Use when: you need range queries like subMap(), floorKey(). 4. Hashtable → Synchronized, no nulls, legacy class. Don't use it. Reach for ConcurrentHashMap instead. 5. ConcurrentHashMap → Thread-safe without locking the whole map. Use when: multiple threads read/write simultaneously. 6. WeakHashMap → Keys are weakly referenced — GC can collect them. Use when: you need memory-sensitive caching (won't cause leaks). 7. EnumMap → Only enum keys, array-backed, blazing fast. Use when: your keys are a fixed enum — state machines, configs. 8. IdentityHashMap → Uses == instead of .equals() for key comparison. Use when: object identity matters — serialization, graph traversal. The rule is simple: Match the map to the problem, not the other way around. Choosing the wrong map is free today. The production bug it causes? Not so free. Save this before your next code review. Repost if your team still uses Hashtable in 2026. Which map do you reach for most — and have you ever regretted it? #Java #SoftwareEngineering #Programming #BackendDevelopment #100DaysOfCode #CleanCode #JavaDeveloper #TechTwitter #CodingTips #DataStructures
To view or add a comment, sign in
-
-
🧠 JVM Memory & Garbage Collection Let me explain Java memory using your HOUSE as an example 🏠👇 🏠 JVM = Your House Your Java app lives here. Different rooms, different purposes. 📦 Heap = The Storeroom All objects go here. Never clean it? It crashes → OutOfMemoryError 💥 Heap has sections: 👶 Young Gen → new stuff (dies fast) 🧓 Old Gen → stuff you kept for years 🏷️ Metaspace → labels about your stuff 🪑 Stack = Your Desk Small, fast. Holds current work (method calls, local variables). Cleans itself when work is done. No GC needed! 🧹 Garbage Collection = Mom Cleaning Your Room “Do you still need this? No? GONE.” Java finds unused objects and removes them automatically. But sometimes GC yells: “EVERYBODY FREEZE while I clean!” ⏸️ These Stop-the-World pauses make apps laggy. 🔧 Choose Your Cleaner: 🟢 G1 → good all-rounder 🔵 ZGC → almost zero pauses 🟡 Shenandoah → low-latency beast 🔴 Serial → tiny apps only 📝 String Pool = Shared Notebook String a = “Hello”; String b = “Hello”; Java keeps ONE copy. Both point to it. Memory saved! 🎯 ⚡ Make Your App Faster: → Create only objects you need → Set unused objects to null → Close DB connections always → Remove unused listeners → Tune heap with -Xms and -Xmx → Profile with VisualVM or JConsole 🚨 Memory Leak Culprits: ❌ Unclosed DB connections ❌ Static lists that grow forever ❌ Listeners never unsubscribed ❌ Huge data in user sessions 🎯 Recap: 🏠 JVM = House 📦 Heap = Storeroom 🪑 Stack = Desk 🧹 GC = Auto cleaner 📝 String Pool = Shared notebook 🚨 Leaks = Stuff you forgot to toss Clean heap = Fast app 🏃💨 #Java #JVM #GarbageCollection #HeapMemory #JavaDeveloper #Programming #CodingTips #SoftwareEngineering #LearnJava #DevCommunity #100DaysOfCode #JavaPerformance #MemoryManagement #CleanCode #JavaInterview #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