ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Stack<T> {
    private List<T> items = new ArrayList<>();
    void push(T item) { items.add(item); }
    T pop() { return items.remove(items.size() - 1); }
    boolean isEmpty() { return items.isEmpty(); }
}
public class Main {
    public static void main(String[] args) {
        Stack<Integer> s = new Stack<>();
        s.push(1); s.push(2); s.push(3);
        StringBuilder sb = new StringBuilder();
        while (!s.isEmpty()) sb.append(s.pop());
        System.out.print(sb);
    }
}
  1. A. 123
  2. B. 321
  3. C. Compilation error: generic class cannot be named Stack (clashes with java.util.Stack)
  4. D. 312

Correct answer: B. 321

A user-defined generic Stack<T> works independently of java.util.Stack; there's no naming clash as long as it isn't imported under the same simple name ambiguously. push 1,2,3 then pop in LIFO order yields 3, 2, 1 — printed as '321'.

More OOP with C++ and Java questions

Exams that ask this topic