0

Why String is immutable?

21st Mar 2019, 1:24 AM
praveen kasojjala
praveen kasojjala - avatar
4 Answers
+ 2
A string is an array of characters and you can address the single characters through their index. str = "Hello" => print(str[0]) (output: "H", works in most languages, probably in Java too). Immutable means that you can't change characters through their index. str[0] = "S" doesn't turn "Hello" into "Sello"
21st Mar 2019, 6:50 AM
Anna
Anna - avatar
+ 1
Because it is predefined class in Java and cannot be changed.A string is an array of characters and you can address the single characters through their index. str = "God" => print(str[0]) (output: "G").Immutable means that you can't change characters through their index. str[0] = "M" doesn't turn "God" into "Mod"
22nd Mar 2019, 5:05 PM
Vidhyasagar Kothale
Vidhyasagar Kothale - avatar
0
Str[0] won't work..If you create a string s1 and perform some operations like concat,But it doesn't change s1 data. A new string Object is created and return to your program. So whatever Operations you perform on String Object it won't Store anywhere, unless you assigned it to a variable.
21st Mar 2019, 10:33 AM
praveen kasojjala
praveen kasojjala - avatar
0
Sagar i don't think so. There are so many predefined classes which are not immutable objects. I want to know what's the reason behind of creating String as immutable.
22nd Mar 2019, 5:14 PM
praveen kasojjala
praveen kasojjala - avatar