ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println((a == b) + " " + (a == c) + " " + a.equals(c));
}
}- A. true true true
- B. false false true
- C. true false true
- D. true true false
Correct answer: C. true false true
String literals are interned in the string pool, so a and b refer to the same pooled object (a == b is true). new String("hello") explicitly allocates a fresh heap object distinct from the pool, so a == c is false. equals() compares contents, which are identical, so a.equals(c) is true.
More OOP with C++ and Java questions
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String c = new…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { List<Integer> nums =…
- What is printed? java public class Main { static void risky(int x) throws Exception { if (x < 0) throw new Exception("neg")…
- What is printed? java public class Main { static String f(int x) { try { if (x == 0) throw new ArithmeticException("div0"); return "ok" +…
- What is printed? java class LowBalanceException extends Exception { LowBalanceException(String m) { super(m); } } class Account { double…
- What is printed? java public class Main { public static void main(String[] args) throws Exception { try { method1(); } catch…