ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
// static methods of the main class:
static void change(StringBuilder sb) {
sb.append("X");
sb = new StringBuilder("Y");
sb.append("Z");
}
// in main:
StringBuilder s = new StringBuilder("A");
change(s);
System.out.print(s);- A. YZ
- B. AX
- C. AXYZ
- D. A
Correct answer: B. AX
Java passes the reference by value. append("X") changes the shared object, so the caller sees AX. Reassigning sb only changes the local copy of the reference; the later YZ object is lost when the method returns.
More OOP with C++ and Java questions
- What is printed? java List<Integer> l = new ArrayList<>(List.of(1, 2, 3)); l.remove(1); System.out.print(l + " ")…
- What is printed? java List<Integer> list = new ArrayList<>(List.of(1, 2, 3)); for (Integer i : list) if (i == 2) list.remove(i)…
- What happens with this C++ code? cpp void f(int a, int b = 0) { cout << "two"; } void f(int a) { cout << "one"; } int main() { f(5); }
- What is printed? cpp struct Base { virtual void show() { cout << "Base "; } }; struct Derived : Base { void show() override { cout <<…
- What is printed? cpp class Base { public: Base() { hello(); } virtual void hello() { cout << "B"; } }; class Derived : public Base {…
- What is printed? cpp struct A { A() { cout << "A"; } }; struct B : virtual A { B() { cout << "B"; } }; struct C : virtual A { C() { cout…