OCA Java SE 8 Core Java APIs - OCA Mock Question Core Java APIs 1-6








Question

Which are the results of the following code? (Choose all that apply)

public class Main{
   public static void main(String[] argv){
         String letters = "abcdef"; 
         System.out.println(letters.length()); 
         System.out.println(letters.charAt(3)); 
         System.out.println(letters.charAt(6));    
   }
}
  1. 5
  2. 6
  3. c
  4. d
  5. An exception is thrown.
  6. The code does not compile.




Answer



B, D, E.

Note

length() counts of the number of characters in a String. It returns 6 as result.

charAt() returns the character at the specified index, which is zero based.

The last character is at the index of length() -1.

A StringIndexOutOfBoundsException is thrown for the last line.


public class Main{
   public static void main(String[] argv){
         String letters = "abcdef"; 
         System.out.println(letters.length()); 
         System.out.println(letters.charAt(3)); 
         System.out.println(letters.charAt(6));    
   }
}