Java memory reference issue

Why does the below mentioned code prints 4,3,2,1,0 and why not 4,4,4,4,4. Since the reference sb is same so why not it pointing towards the last updated value and why not it updating all the values as 4

package iteration;

import java.util.Stack;

public class test {

    public static void main(String[] args) {
        Stack stack = new Stack();
        StringBuilder sb;
        for (int i = 0; i < 5; i++) {
             sb = new StringBuilder();
            sb.append(i);
            stack.add(sb);
        }

        for (int i = 0; i < 5; i++) {
            System.out.println(stack.pop());
        }
    }
}
Jon Skeet
people
quotationmark

Since the reference sb is same

It's not. You're using the sb variable each time, but each time you call stack.add(sb) it's adding "the current value of sb" which is different on each iteration due to this line:

sb = new StringBuilder();

It's very important to understand the difference between "a variable" and "the value that a variable currently holds".

When you execute stack.add(sb);, that evaluates the current value of sb (which will be a reference to a StringBuilder instance) and then passes that reference to Stack.add. When you later change the value of sb, that doesn't change the value on the stack.

Now, compare that with this code:

StringBuilder sb = new StringBulder();
for (int i = 0; i < 5; i++) {
    sb.append(i);
    stack.add(sb);
}

At that point, you'd have 5 references to the same StringBuilder object on the stack, and you'd print out "01234" five times. This time you're modifying the content of the existing object, rather than changing sb's value.

people

See more on this question at Stackoverflow