Could I change the reference inside one method with this reference as argument in Java?

In Java arguments are passed by value, object arguments pass a reference to the object, this means that you can change the reference of the argument, but that does not change the object you passed the reference to. You have two possibilities, return the new object (preferred) or pass reference to a container that can receive the new reference (collection, array, etc.) For example:

private static String changeStringAndReturn(String s) {
    return new String("new string");
}
private static void changeStringInArray(String[] s) {
    if (null != s && 0 < s.length) {
        s[0] = new String("new string");
    }
}

References in Java are passed by value, so even if you modify the reference inside the function, changes won't be reflected back to the calling function because what you modify inside the function is just a copy of the original reference not the original reference itself.

But you can return the new string from your changeString method instead of trying to modify the reference there(inside the function) itself.


Only if you make the function

private static void changeString(String[] s) {
    s[0] = new String("new string");
}

String are immutable, and Java has no concept of a 'pointer-to-a-reference' as a first class datatype. If you don't like the above, you can make a little class containing a single String field.