Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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

1 Answer

0 votes
by (46k points)

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";

Browse Categories

...