-2

When passing String a to myFunction() , I pass the reference. Why when it exits, the reference points to the old String ? Doesn't it use the real reference to the string ?

import java.time.*;

public class Main {
    public static void main(String[] args) {
        String a = "aaa";

        myFunction(a);

        System.out.println(a);
    }

    private static void myFunction(String a) {
        a = a + "111";
        System.out.println(a);
    }
}
Mihai
  • 101
  • 2
  • 2
  • 8
  • You may either pass for instance a `StringBuilder` since this can be modified by the method, or return a result `String` from the method. Java strings are unmodifiable (constant, frozen). – Ole V.V. Oct 11 '16 at 10:29
  • To answer your question, the reference is passed into the method only. If the reference is changed in the method, the new reference is not passed back out. – Ole V.V. Oct 11 '16 at 10:31

1 Answers1

0

Look into variable scope. You are creating a local copy of the a variable and setting it in the myFunction() . The local copy only lives as long as the method does. When the Myfunction() completes its modified copy of the "a" is no longer reachable.

Reign
  • 289
  • 1
  • 9