ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
String target = new String("b");
System.out.print(list.contains(target) + " " + list.indexOf(target));
}
}- A. true 1
- B. false -1
- C. true 0
- D. Compilation error: contains requires ==, not equals
Correct answer: A. true 1
List.contains() and indexOf() use equals(), not ==, to compare elements. String correctly overrides equals() by content, so the non-pooled `new String("b")` still matches the pooled "b" in the list at index 1.
More OOP with C++ and Java questions
- 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…
- What is printed? cpp struct Base { Base() { cout << "Base "; } }; struct Mixin1 { Mixin1() { cout << "Mixin1 "; } }; struct Mixin2 {…
- What is printed? java class Base { public String describe() { return "Base"; } } interface Describable { String describe(); } class Sub…