2

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());
        }
    }
}
3
  • Because pop removes the last item. Use peek instead. Also I don't understand why do you have a StringBuilder there.. Commented May 21, 2015 at 10:34
  • @MarounMaroun: I think you've misunderstood the problem. Commented May 21, 2015 at 10:37
  • 1
    @JonSkeet Indeed. After reading your answer I realized that. It was my instinct when I saw "4,3,2,1", "4,4,4,4" and "Stack" in the same sentence :) Commented May 21, 2015 at 10:38

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You need StringBuilder sb = new StringBuilder(); being placed outside for loop to reference to the same object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.