The question asked lot of time to lot of people. Each has some reasons for immutability of java strings.
Java has primitive types which are inherently immutable.
int i = 0;
void changeValue(int val) {
val = 1;
}
changeValue(i);
Value of "i" is still 0.
The same way strings are just sequence of character. It should be primitive as well. It brings peace of mind with it.
As primitive has + and - operations strings also have concatenation and substring operations. String is not primitive so java has workaround for it and made it feels like primitive.
All this lead us to immutable string object.
The same rules applied to other java objects like. All wrapper classes (Integer, Float etc.), BigDecimal, BigInteger, Color etc.
Java has primitive types which are inherently immutable.
int i = 0;
void changeValue(int val) {
val = 1;
}
changeValue(i);
Value of "i" is still 0.
The same way strings are just sequence of character. It should be primitive as well. It brings peace of mind with it.
As primitive has + and - operations strings also have concatenation and substring operations. String is not primitive so java has workaround for it and made it feels like primitive.
All this lead us to immutable string object.
The same rules applied to other java objects like. All wrapper classes (Integer, Float etc.), BigDecimal, BigInteger, Color etc.
Comments
Post a Comment