ProgrammingModerateProduct-company placement · Java
What is printed?
What is printed?
// static methods of the main class:
static void up(String s) { s = s.concat("X"); }
static void add(StringBuilder b) { b = new StringBuilder("new"); b.append("!"); }
// in main:
String s = "abc";
StringBuilder b = new StringBuilder("old");
up(s); add(b);
System.out.print(s + " " + b);- A. abcX old
- B. abc old
- C. abc new!
- D. abcX new!
Correct answer: B. abc old
Both methods only reassign their own parameter copies; the append goes to the new builder. Nothing reachable from the caller's variables is changed.
More OOP with C++ and Java questions
- What is printed? java Object a = new ArrayList<String>(); List<Integer> b = new LinkedList<>(); List<Integer> c = new ArrayList<>()…
- What happens when this interface is compiled? java interface Named { String name(); default boolean equals(Object o) { return o instanceof…
- Which of these is a valid functional interface (usable as a lambda target)?
- What is printed? java class T { String name = "outer"; void run() { Runnable a = () -> System.out.print(this.name + " "); Runnable b = new…
- What is printed? java // Java 16 or later record P(int x, int y) { } // in main: P a = new P(1, 2), b = new P(1, 2); System.out.print((a…
- What happens when this is compiled? java class P { P(int x) { } P() { } } class C extends P { } // in main: C c = new C(5);