Java OCA OCP Practice Question 1414

Question

What is the result of the following?

package mypkg; //from ww  w . j av a 2 s.com
public class Main { 

   public static void m(String... names) { 
      int l = names[1].length();       // s1 
      System.out.println(names[l]);    // s2 
   } 

   public static void main(String[] args) { 
      m("Summer", "Fall", "Winter", "Spring"); 
   } 
} 
  • A. Fall
  • B. Spring
  • C. The code does not compile.
  • D. The code throws an exception on line s1.
  • E. The code throws an exception on line s2.


E.

Note

The code does compile.

Line s1 is tricky because length is used for an array and length() is used for a String.

Line s1 stores the length of the Fall in a variable, which is 4.

Line s2 throws an exception because 4 is not a valid index for an array with four elements.

Remember that indices start counting with zero.

Therefore, Option E is correct.




PreviousNext

Related