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));
    }
}
  1. A. true 1
  2. B. false -1
  3. C. true 0
  4. 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

Exams that ask this topic