+ 7

What are the main problems we can face by String immutability in java ?

Scince we know that String is an immutable class in java so by that immutability behaviour we might be face some problems as well as advantages .

18th Nov 2018, 11:45 AM
Surya Pandey
Surya Pandey - avatar
5 Respostas
+ 8
The main problem is that when you need to concat a lot of strings, if you concat it to the old string then many memory will be used because each concatenation will create another reference in memory, this affects the performance of your program, the correct way to do it is using StringBuffer or StringBuilder.
18th Nov 2018, 4:09 PM
Diogo
Diogo - avatar
+ 6
There can be some other limitations(I wouldn't say problem) but I can tell you about a major one. Once a String is created then it can't be changed anymore! The code I am adding below will give you a clearer idea. https://code.sololearn.com/c8QAJAu8k92D/?ref=app
18th Nov 2018, 3:23 PM
Sadman Sakib
Sadman Sakib - avatar
+ 5
Ok....so let me tell you one important thing Use String class when you know that you don't have to perform any operation because for every operation String class creates a new object which is not good in terms of of memory management. Use StringBuilder class when you have to perform many operations on string because StringBuilder won't creates different objects for every string operation
19th Nov 2018, 9:34 AM
Rishi Anand
Rishi Anand - avatar
+ 5
In java a new String is a new object when it is changed every time. Creating a new object each time can be costly. Thats why there is stringbuffer etc, these usually work with char arrays where chars are added or where multiple string are referenced withouth instantiating new ones for every combination. Then when you want the result it creates just 1 new string for the response. Resulting in less String instantiations.
19th Nov 2018, 10:17 AM
Koen Rockstars
Koen Rockstars - avatar
+ 2
Depends on how and where you use it. Sometimes it has adavantaged over other data type. But mainly it the desavagteges related to memory management
19th Nov 2018, 7:46 AM
Idris Tuna