String s = ...;
s = s.substring(1);
Is this possible? I thought you can't change a String object in Java.
The String is immutable, so its value cannot be changed. If the String doesn't remain immutable, any hacker can cause a security issue in the application by changing the reference value. The String is safe for multithreading because of its immutableness.
Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.
Strings are immutable in Python. As you can see, the replace method doesn't change the value of the string t1 itself. It just returns a new string that can be used for other purposes.
It is because all primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.
In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable. Once String object is created its data or state can't be changed but a new String object is created.
String objects are immutable. String references, however, are mutable. Above, s
is a reference.
String objects are immutable, meaning that the value of the instance referred to by s
cannot change.
Your code does not mutate the instance.
Rather, it changes the s
reference to refer to a new string instance.
For example:
String a = "1";
String b = a;
a = "2";
After executing this code, b
is still "1"
.
The line b = a
sets b
to refer to the same "1"
instance that a
currently refers to.
When you subsequently write a = "2"
, you are changing the a
variable to refer to a different ("2"
) instance.
However, the original "1"
instance, which b
still refers to, has not changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With