ProgrammingHardWipro · Cognizant 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.print((a == b) + " " + (a == c) + " " + a.equals(c));
}
}- A. true true true
- B. true false false
- C. true false true
- D. false false true
Correct answer: C. true false true
String literals are interned, so a and b refer to the same object in the string pool: a == b is true. new String("hello") always creates a distinct heap object outside the pool, so a == c is false, even though the characters 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 = new String("hi").intern(); String b = "hi"…
- What is printed? java class Box { int value; Box(int v) { value = v; } } public class Main { public static void main(String[] args) { Box…
- Which statement about overriding equals() correctly describes the contract that must hold?
- What is printed? java class Animal { String name; Animal(String n) { name = n; } @Override public boolean equals(Object o) { if (!(o…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; int b = 127; System.out.print(a == b)…
- What is printed? java public class Main { public static void main(String[] args) { String s1 = "java"; String s2 = "java".intern(); String…