For loop consists of 3 expressions: initialization, termination, increment:
for (initialization; termination; increment) {
//
}
- initialization is executed only once
- termination is executed each iteration
- increment is executed each iteration
In your case you retrieve from the stack twice on the first iteration, hence your problem with a non-printing element.
You might be wondering why does it print 3,2
and not 2,1
? That's because increment expression is invoked after (in the very end) each iteration through the loop.
All of sections are optional, so you can iterate this way:
for (; ; ) {
System.out.println(s.pop());
}
... and you will eventually have java.util.EmptyStackException
on an attempt to pop an element from already empty stack.
So the most basic way to iterate over a stack with a for loop is to make use of termination statement as a "safe-check":
for (; !s.isEmpty(); ) {
System.out.println(s.pop());
}
... which is basically a more complex and counterintuitive way to write a while
-loop:
while (!s.isEmpty()) {
System.out.println(s.pop());
}
Docs:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html