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);
}
}- A. 123
- B. 321
- C. Compilation error: generic class cannot be named Stack (clashes with java.util.Stack)
- 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
- Which statement is correct? java class Event { protected void log() { System.out.print("Event.log"); } } class ClickEvent extends Event {…
- What is printed? java class Base { public Base() { System.out.print("Base "); } public Base(Base other) { System.out.print("BaseCopy "); }…
- What is printed? cpp struct Base { virtual void run() { step1(); step2(); } virtual void step1() { cout << "B1 "; } virtual void step2() {…
- What is printed? java class Account { protected double balance; Account(double b) { balance = b; } void transfer(Account to, double amt) {…
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(int x) { cout << "Base(" << x << ") "; } }; struct Derived : Base {…
- What is printed? java class Node<T> { T value; Node<T> next; Node(T v) { value = v; } } public class Main { static <T> int length(Node<T>…