0

I am unable to determine why the sb object reference value that gets mirrored back to the calling method does not mirror the last value (i.e. null) that it was assigned?

  public class Test{
   void testRefs(String str, StringBuilder sb){
    str = str + sb.toString();
    sb.append(str);
    System.out.println(sb);
    str = null;
    sb = null;
    System.out.println(sb);
  }


  public static void main(String[] args){
    String s = "aaa";
    StringBuilder sb = new StringBuilder("bbb");
    new Test().testRefs(s, sb);
    System.out.println("s="+s+" sb="+sb);
  }
}
Michael
  • 63
  • 1
  • 1
  • 10
  • 2
    Read, no study, this duplicate: [Is Java “pass-by-reference” or “pass-by-value”?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). It will explain all. – Hovercraft Full Of Eels May 28 '18 at 02:04
  • 1
    Because Java is always pass-by-value always, you can change the *state* of a reference parameter within the method but you can't change the ***reference*** itself which is what you're trying to do. – Hovercraft Full Of Eels May 28 '18 at 02:07

0 Answers0