+ 3

Who knows the weakness of string in Java? And how to surpass it?

changing the string value

11th Apr 2017, 9:00 PM
Fethi HADJ ABDELKADER
Fethi HADJ ABDELKADER - avatar
10 Answers
+ 14
In Java a String object is not changed. There will always be a new String object and the old one gets garbage collected if no variable refers to it anymore. Wouldn't call it weak, because it has it's benefits, see https://www.sololearn.com/discuss/240637/?ref=app
11th Apr 2017, 9:07 PM
Tashi N
Tashi N - avatar
+ 11
@Fethi So you try to understand why there are different classes for strings in Java? The differences are (im)mutability and thread safeness. This might help you: http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html?m=1
12th Apr 2017, 7:28 PM
Tashi N
Tashi N - avatar
+ 9
@Fethi There is a difference between class Integer and primitive datatype int in Java. Integer wraps an int in an object. Like String, Integer is immutable, so a new object is created when you change the value that is boxed in an Integer.
12th Apr 2017, 4:35 PM
Tashi N
Tashi N - avatar
+ 7
That can't be called a weakness. If you want to change, there is StringBuilder, right?
12th Apr 2017, 4:54 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 7
@Krishna If I can not lift a chair that can't be called a weakness, right? If we need to lift, there are other people around, right? ;-)
12th Apr 2017, 3:26 PM
Andrew Harchenko (Tomsk)
Andrew Harchenko (Tomsk) - avatar
+ 6
And for the second part of Q: You could use StringBuilder instead. (I think it's a question from interview, isn't it? So, add-on: such "not_changeable" objects are called "immutable")
11th Apr 2017, 9:50 PM
Andrew Harchenko (Tomsk)
Andrew Harchenko (Tomsk) - avatar
+ 6
@Fethi Tashi N has answered you question, so I (and William) made an add-on to her answer (and William too). That's the cause of "and"... and your message is unclear: What are you talking about now? Class int? Int is not a class...
12th Apr 2017, 3:23 PM
Andrew Harchenko (Tomsk)
Andrew Harchenko (Tomsk) - avatar
+ 4
and a HUGE benefit of String being Immutable is being thread safe, makes coding a lot simpler when multithreading, and as mentioned there's many ways to overcome this such as StringBuilder
12th Apr 2017, 12:23 AM
William La Flamme
William La Flamme - avatar
+ 1
@Andrey kharchenko @William La Flamme, your answers begins with "And" or there is a cut of text?. I think Class int doesn't need to create a new Class (IntBuilder or IntBuffer or else) to execute any methode we invoke on it, if so, class int is not a complet (=>weak) class on the integer.
12th Apr 2017, 6:29 AM
Fethi HADJ ABDELKADER
Fethi HADJ ABDELKADER - avatar
0
sorry, I give a bad example(yes int is primitive data type and integer is a object class), but string is an object class and stringbuilder and stringbuffer are all objects classes.
12th Apr 2017, 7:24 PM
Fethi HADJ ABDELKADER
Fethi HADJ ABDELKADER - avatar