Arindam Pal’s Post

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

To view or add a comment, sign in

Explore content categories