+ 1

Why String is immutable in java

22nd Feb 2019, 12:11 PM
Naresh Deeti
Naresh Deeti - avatar
3 Respostas
+ 6
Important Facts About Strings and Memory! One of the key goals of any good programming language is to make efficient use of memory. As an application grows, it's very common for string literals to occupy large amounts of a program's memory, and there is often a lot of redundancy within the universe of String literals for a program. To make Java more memory efficient, the JVM sets aside a special area of memory called the String constant pool. When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. (The existing String simply has an additional reference.) Now you can start to see why making String objects immutable is such a good idea. If several reference variables refer to the same String without even knowing it, it would be very bad if any of them could change the String's value. . . .
22nd Feb 2019, 12:32 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 5
. . . #2 You might say, "Well that's all well and good, but what if someone overrides the String class functionality; couldn't that cause problems in the pool?" That's one of the main reasons that the String class is marked final. Nobody can override the behaviors of any of the String methods, so you can rest assured that the String objects you are counting on to be immutable will, in fact, be immutable.
22nd Feb 2019, 12:36 PM
Danijel Ivanović
Danijel Ivanović - avatar
24th Feb 2019, 3:49 PM
Danijel Ivanović
Danijel Ivanović - avatar