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());
}
}
}
popremoves the last item. Usepeekinstead. Also I don't understand why do you have aStringBuilderthere..