Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Trial67
{
    public static void main(String[] args)
    {
        List<Integer> l = new ArrayList<Integer>(
            Arrays.asList(10, 20, 30));
        System.out.println(
            l.contains(20) + " " + l.indexOf(40) + " " + l.get(l.indexOf(30)));
    }
}

  • A.The program prints true -1 40
  • B.The program prints true 0 30
  • C.The program prints true -1 30
  • D.The program prints false -1 30

Answer: C

contains reports the presence of a value by equality, indexOf returns -1 for something absent rather than throwing, and the last call looks up the index of 30 and reads it back. Feeding an unchecked -1 from indexOf into get is the bug this sentinel invites.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.