ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
// in main:
String s = "hello";
s.concat(" world");
System.out.println(s);
String t = s.concat(" world");
System.out.println(t);- A. hello world then hello world
- B. hello then hello world
- C. hello world then hello
- D. hello then hello
Correct answer: B. hello then hello world
Strings are immutable: s.concat(" world") returns a NEW string without modifying s, so the ignored first call changes nothing, and the first println still prints "hello". The second call captures the returned new string into t, so the second println prints "hello world".
More OOP with C++ and Java questions
- What is printed? java class Node { int val; Node(int v) { val = v; } @Override public int hashCode() { return 42; } @Override public…
- What is printed? java // in main: String a = "Hello".toLowerCase(); String b = "hello"; System.out.println((a == b) + " " + a.equals(b));
- Which overridden equals() below is actually BROKEN with respect to the symmetry requirement of the equals contract? java class A { int x…
- What is printed? java class Version { int major, minor; Version(int ma, int mi) { major = ma; minor = mi; } @Override public boolean…
- What is printed? java public class Main { static int f() { int x = 10; try { return x; } finally { x = 20; } } public static void…
- What is printed? java public class Main { public static void main(String[] a) { try { System.out.print("A"); throw new RuntimeException()…