0

I know that String are immutable and once created they cannot change their values. If so, please guide me to understand what is "wrong" with my code as apparently I was able to change the value of the initial String. Thanks in advance

package ocajp;

public class TStatic1 {
    
    static String s1 = "Ann";
    static void change() {  s1 += " has apples";}
    
    public static void main(String[] args) {
        change();
        System.out.println("s1: " + s1);
    }
}

s1: Ann has apples

Josh
  • 3
  • 3
Unix
  • 17
  • 1

2 Answers2

4

You need to distinguish between objects and references: objects of type String are immutable. However, the variable s1 is a reference to an object of type String.

What your code does is create a new string via concatenation, and then modify the reference s1 to refer to this newly created string.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • you're right @Konrad Rudolf, this new one confirms it. Thank you package ocajp; public class TStatic1 { static String s1 = new String("Ann"); static String change(String input) { input += " has apples"; return input; } public static void main(String[] args) { change(s1); System.out.println("s1: " + s1); } } //brings: //s1: Ann – Unix Jan 29 '21 at 10:55
1

You actually created new object for s1 variable same as If you did String newString = s1 + " has apples".

And original s1 variable is referenced to this newly created String object