+ 10
String are immutable. What is this exactly ? Can any one give a example?
Immutable means cannot modifiable. But In this Ex: String s1="ab",s2="cd"; s1=s1+s2; Here output is s1="abcd"; s1=s1.UpperCase(); Then here output is s1="ABCD"; Why not giving errors? s1 is modifying its value. Why?
21 ответ
+ 8
Maybe this can help you to understand in a better way
https://www.javatpoint.com/immutable-string
+ 6
In c++ you can change the string s character in middle but in python u can't do it .The only way do to it is create a new string and assign it to same variable
+ 5
Strings are immutable, in the example you did not change the strings.
Reassigning string variables do not change the strings.
Reassigning string variable will destroy old string and replace it with a new string.
+ 3
s1 is not modifying it's values.. Recently i had to give a presentation on the same so i had found why this happens...
Well in the first case s1="ab"
This creates an object s1 with value ab.. This object takes some place in the heap.
Now s2="cd"
This creates an object s2 with value cd.. This object again takes some place in the heap.
Now when you do a=a+b or a=a.concat(b)
A new object is created and this again occupies more memory in the heap..
So you're not modifying the previous object instead you're creating a new object..
/*Wastage of memory*/
To avoid this we use StringBuffer/StringBuilder classes in Java 👍
Hope you got it
I had referred this link:
https://medium.com/@abhiroop.nray/understanding-string-in-java-31519b8d7b9c
P.s to be more specific the reference variable is assigned and the stuff gets more detailed.. Let's not get there 😁
+ 2
Jaya krishna I don't see any difference between strings and integers according immutability.
+ 2
A J thank you.
The Link helped me to get clarity.. I read similar long ago. but i thought reassigning is also not possible. Gone to start point to rethinking..
But this actually leads a lot of wastage of garbage
collection .. ? need to know about it.
+ 2
jtrh
Seb Thes
rodwynnejones
A J
Thank you very much to all of you for your replays..
Please share if you any advanced info about this in security with strings and garbage collection,