Sajal Shrivastav’s Post

Something new I learned about Java Strings Why does this print true? 👉 String a = "Peter"; String b = "Peter"; System.out.println(a == b); Because of the String Constant Pool. Java stores string literals in a special memory area. If the value already exists, it reuses the same reference. Now look at this: 👉 String a = new String("Peter"); String b = new String("Peter"); Now a == b is false. Why? Using new forces Java to create a new object in heap memory, even if the same value exists in the pool. Why does Java do this? To optimize memory usage. Since Strings are immutable, Java can safely reuse the same object for identical literals. 💡 Key takeaway: == compares references .equals() compares actual content #Java #JavaDeveloper #BackendDevelopment #SpringBoot #SoftwareEngineering #LearningInPublic

You should also see about intern() in String

To view or add a comment, sign in

Explore content categories