Java String Creation Methods: Literal vs new String()

📌 new String() vs String Literal in Java In Java, Strings can be created in two different ways. Although they may look similar, they behave differently in memory. 1️⃣ String Literal   When a String is created using a literal: • The value is stored in the String Pool   • JVM checks if the value already exists   • Existing reference is reused if available  Example: String s1 = "java"; String s2 = "java"; Both references point to the same object. 2️⃣ new String()   When a String is created using the `new` keyword: • A new String object is created in heap memory   • It does not reuse the String Pool object by default  Example: String s3 = new String("java"); `s3` points to a different object even if the value is the same. 3️⃣ Memory Impact   • String literals reduce memory usage through reuse   • `new String()` always creates an additional object   • Using `new` unnecessarily can increase memory consumption  4️⃣ When to Use   • Prefer String literals for most use cases   • Use `new String()` only when a distinct object is explicitly required  💡 Key Takeaways: - String literals use the String Pool   - `new String()` creates a separate heap object   - Understanding this helps write memory-efficient code #Java #CoreJava #String #JVM #BackendDevelopment

To view or add a comment, sign in

Explore content categories