-1

Possible Duplicate:
Is Java “pass-by-reference”?

Why does the code below print 'test' instead of throwing a NullPointerException?

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    sb.append("test");
    append(sb);
    System.out.println(sb.toString());
}

public static void append(StringBuilder sb) {
    sb = null;
}
Community
  • 1
  • 1
Bordor Turtle
  • 51
  • 1
  • 4
  • 1
    If you step through your code in a debugger you will see what each line of code is doing and it will make this much clearer. – Peter Lawrey Aug 09 '12 at 12:59

3 Answers3

5

You are setting the local variable sb in the method append() to null - that does not affect the calling environment's variable, it remains the same.

amit
  • 175,853
  • 27
  • 231
  • 333
0

Because your custom append model isn't returning sb back to the parent method. and therefore System.out.println(sb.toString()); is simply returning the sb method in the current context.

kolin
  • 2,326
  • 1
  • 28
  • 46
0

Because if you a assign a value to a method parameter, it maintains the new value only within the scope of that method. In other words it would throw a NPE if you placed the System.out.println(sb) inside the append method.

Leigh
  • 28,765
  • 10
  • 55
  • 103
Jan Hruby
  • 1,477
  • 1
  • 13
  • 26