Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What\'s the output of this code? Stack s = new Stack<Integer>(); s.push(7); s.pu

ID: 654571 • Letter: W

Question

What's the output of this code?

Stack s = new Stack<Integer>();
s.push(7);
s.push(10);
System.out.println(s.pop());
System.out.println(s.peek());
s.push(3);<br>
s.push(5);<br>
System.out.println(s.pop());
System.out.println(s.isEmpty());
System.out.println(s.size());
System.out.println(s.peek());
s.push(8);
System.out.println(s.pop());
System.out.println(s.pop());

I was thinking it was 7 at first and then I thought it was [8,3,7] but neither of those are right. Help please! I know "pop" means that it removes the top number, "peek" returns the top element, and that "push" just adds to the stack.

Explanation / Answer

Stack s = new Stack<Integer>();
s.push(7); // now stack contains 7
s.push(10); // now stack contains 10 7 (10 being top element)
System.out.println(s.pop()); //it will prnit 10, pop not only removes element but returns top element.
System.out.println(s.peek()); // it will print 7, next element in stack. now stack contains 7
s.push(3); // now stack contains 3 7
s.push(5); // now stack contains 5 3 7
System.out.println(s.pop()); ///it will prnit 5, pop not only removes element but returns top element.
System.out.println(s.isEmpty()); // false as stack is not empty (it has elements 3 7).
System.out.println(s.size()); // 2. as stack contains 3 7
System.out.println(s.peek()); // get top element 3.
s.push(8); // now insert 8 into stack now stack as 8 3 7.
System.out.println(s.pop()); // it prints 8, last element inserted into stack, now stack contains 3 7
System.out.println(s.pop()); // it prints 3, next element in stack, now stack contains 7.

Output is :
10
7
5
false
2
3
8
3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote