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

Discussion

What will be the output of the program?

public class Example07
{
    private static void report()
    {
        String greeting = "hello";
        int first = greeting.indexOf("l");
        int last = greeting.lastIndexOf("l");
        System.out.println(first + " " + last);
    }

    public static void main(String[] args)
    {
        report();
    }
}

  • A.The program prints 2 2
  • B.The program prints 3 3
  • C.The program prints 2 3
  • D.The program prints 3 2

Answer: C

indexOf scans from the start and finds the first l at position 2, while lastIndexOf scans from the end and finds one at position 3. Both indices are zero-based. A missing character would give -1 from either method rather than an exception.

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

Post your comment

Please log in or register to post a comment.