← Back to libraryQuestion 49 of 273
JavaIntermediate

String Pool and String Literals

📖 Detailed Explanation:

Java maintains a String Constant Pool for memory efficiency. String literals ("hello") are stored in the pool. If you create another String with the same value, Java reuses the same object from the pool rather than allocating new memory. String objects created via 'new' are allocated on the heap, bypassing the pool.

🌍 Real-World Example:

String s1 = "java"; String s2 = "java"; // s1 == s2 (same pool object) String s3 = new String("java"); // s3 != s1 (different heap objects)

🎯 Scenario-Based Interview Question:

What's the difference between String s = "java"; and String s = new String("java");?