1

in "Oracle Certifi ed Associate Java SE 8 Programmer I Study Guide" speaking about passsing by value , saying : Calling methods on a reference to an object does affect the caller

 public static void main(String[] args) {
    StringBuilder name = new StringBuilder();
    speak(name);
    System.out.println(name); // Webby
    }
    public static void speak(StringBuilder s) {
    s.append("Webby");
    }

In this case, the output is Webby because the method merely calls a method on the parameter. It doesn’t reassign name to a different object.

enter image description here

So what does this mean? I didn't get it. Shouldn't there be 2 different objects?

vefthym
  • 7,422
  • 6
  • 32
  • 58

1 Answers1

0

Java passes object parameters as a copy of the reference to the original object. This means that the StringBuilder passed to speak() as s is the very same StringBuilder instance as in the main function, and calling methods on it will affect it in both of your methods. However, if you were to point s inside speak() to another instance of StringBuilder, it wouldn't affect StringBuilder name in the main() function.

Steve Smith
  • 2,244
  • 2
  • 18
  • 22