Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aren't String objects in Java immutable? [duplicate]

String s = ...;

s = s.substring(1);

Is this possible? I thought you can't change a String object in Java.

like image 804
Brandon Avatar asked Aug 03 '10 15:08

Brandon


People also ask

Are string objects immutable 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.

Are objects immutable in Java?

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.

Is string replace 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.

Is Double object immutable in Java?

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.

Is string objects are immutable they Cannot be changed?

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.


2 Answers

String objects are immutable. String references, however, are mutable. Above, s is a reference.

like image 69
Andy Thomas Avatar answered Nov 13 '22 09:11

Andy Thomas


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.

like image 42
SLaks Avatar answered Nov 13 '22 10:11

SLaks