-1

I do know that when you pass an array as a parameter into a method and then alter it in some way, the original array will be changed. However, does this also apply to Strings?

If you have these variables:

int[] testArray = {1,2,3};
String testString = "helloWorld";

And these methods:

static int[] changeFirstEntryToZero(int[] array) {
        array[0] = 0;
        return array;
}

static String changeString(String s) {
        s = "changed";
        return s;
}

And then in the main method you do this:

System.out.println(testArray[0]);
changeFirstEntryToZero(testArray);
System.out.println(testArray[0]);

System.out.println(testString);
changeString(testString);
System.out.println(testString);

Then the result is this:

1

0

helloworld

helloworld

That tells me that it does not permanently change the String. But why?

I thought that Strings are objects too in Java. Is there something I'm missing, or is it that simple?

Could a String accidentally be permanently changed if I did something slightly different.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
grecode97
  • 15
  • 2
  • String is immutable, better to check this https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java – Apar Feb 13 '23 at 11:54
  • You are modifying (the contents of) the array, but you are not modifying the string, you are assigning a different string to the parameter. – Mark Rotteveel Feb 13 '23 at 13:20

1 Answers1

1

In your first method:

static int[] changeFirstEntryToZero(int[] array) {
    array[0] = 0;
    return array;
}

when you use array[0] = 0 you are deferencing the array and accessing the first element of the original array passed to the method. You may conceptually think of passing an array as passing a reference to the original array.

On the other hand, in the second method:

static String changeString(String s) {
    s = "changed";
    return s;
}

the string s is a variable which is local to the method. When the method is called, it will be assigned the value of the string being passed in. However, making an assignment to s only affects this local string, and not the original string which was passed in.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360