ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
String s = "hello";
String t = s;
t = t.concat(" world");
System.out.print(s + " | " + t);
}
}- A. hello | hello world
- B. hello world | hello world
- C. hello | hello
- D. Compilation error: t is already assigned to s
Correct answer: A. hello | hello world
Strings are immutable: concat() returns a brand-new String rather than modifying in place. t is reassigned to point at that new string, but s still refers to the original, unmodified "hello".
More OOP with C++ and Java questions
- What is printed? java public class Main { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object()…
- What is printed? java public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("a"…
- What is printed? java class Key { final String name; Key(String n) { name = n; } @Override public boolean equals(Object o) { if (this ==…
- What is printed? java public class Main { public static void main(String[] args) { String a = "Hello"; String b = "hello"…
- What is printed? java class Base { Base() { System.out.print("Base "); } protected Base(int x) { System.out.print("Base(int) "); } } class…
- What is printed? java class Vehicle { void start() { System.out.print("Vehicle-start "); } } class ElectricCar extends Vehicle { @Override…