InterviewSolution
| 1. |
Why are Java Strings immutable in nature? |
|
Answer» String OBJECTS in Java are immutable by definition. This signifies that the String object's state cannot be changed once it has been created. As a result, if you try to UPDATE the value of that object rather than the values of that object, Java creates a new string object. Because String objects are often cached in the String pool, Java String objects are immutable. Because String literals are frequently shared among numerous clients, one client's action may have an impact on the others. It improves the application's SECURITY, caching, synchronization, and performance by doing so. To begin, we've developed a string literal “Python” that runs in the pool. The string “Data Science” is then formed, and it is also used in the pool. Finally, we've constructed the “Python” string once more. However, JVM checks for the string at this point and finds that the string literal is indeed present. INSTEAD of creating a new String pool instance, it returns the pooled instance's reference, i.e. str1. Similarly, if we use the new keyword to produce string literals, we're using the String pool. Three string literals have been created: “Java”, “C++”, and “Data Science”. We can see that string literals in “Java” and “C++” are new. However, there is already a “Data Science” literal in the pool. JVM now allocates SPACE in the Java heap for the literal “Data Science”. It's important to remember that all String literals formed with the new keyword are stored in the Java heap, not the String pool. |
|