Alex Rivera | Logout

String is immutable. What exactly is the meaning?

Asked 2012-01-10T04:04:14.470
231

I wrote the following code on immutable Strings.

public class ImmutableStrings {

    public static void main(String[] args) {
        testmethod();
    }

    private static void testmethod() {
        String a = "a";
        System.out.println("a 1-->" + a);
        a = "ty";
        System.out.println("a 2-->" + a);
    }
}

Output:

a 1-->a  
a 2-->ty

Here the value of variable a has been changed (while many say that contents of the immutable objects cannot be changed). But what exactly does one mean by saying String is immutable? Could you please clarify this topic for me?

source : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Edit
Report

2 Answers

19

You're changing what a refers to. Try this:

String a="a";
System.out.println("a 1-->"+a);
String b=a;
a="ty";
System.out.println("a 2-->"+a);
System.out.println("b  -->"+b);

You will see that the object to which a and then b refers has not changed.

If you want to prevent your code from changing which object a refers to, try:

final String a="a";
answered 2012-01-10T04:07:25.570
2

You are actually getting a reference to a new string, the string itself is not being changed as it is immutable. This is relevant.

See

Immutable objects on Wikipedia

answered 2012-01-10T04:07:58.270

Your Answer