← Back to libraryQuestion 15 of 273
JavaIntermediate

Strings and Immutability

📖 Detailed Explanation:

Strings in Java are immutable—once created, they cannot be changed. When you 'modify' a string using operations like concatenation or substring(), Java actually creates a brand new string object and stores it in the String Constant Pool (or heap). This design ensures thread safety and allows the JVM to cache identical string values.

🌍 Real-World Example:

If you write on a stone tablet and want to change it, you don't erase the old content; you carve a new tablet and throw the old one away.

🎯 Scenario-Based Interview Question:

If you are concatenating 1,000 strings in a loop using the '+' operator, should you use String or StringBuilder? Why?