5.5k views
5 votes
What will be printed by the following code?

String s = "Animal";
System.out.println(s.indexOf("an"));

User Neiker
by
7.2k points

1 Answer

3 votes

Final answer:

The provided code will print -1 because the indexOf method in Java is case-sensitive and the substring "an" does not appear in the exact casing within the string "Animal".

Step-by-step explanation:

The code provided shows a method call to indexOf on a String object in Java. Specifically, it searches for the substring "an" within the string "Animal". The indexOf method is case-sensitive and will return the index of the first occurrence of the substring if found, or -1 if not found. Since "an" does not appear in the string "Animal" with the same casing, the output will be -1.

Examples:

  • If the code was s.indexOf("An"), the result would be 0 because "An" appears at the beginning of the string "Animal".
  • If the code was s.indexOf("al"), the result would be 4 because "al" is found starting at the fifth character (index 4 as indexes start at 0).

The code will print 2.

User Caopeng
by
6.7k points