Java OCA OCP Practice Question 792

Question

Given:

public class Main{ 
     public static void main (String [] args){ 
     int i = Integer.parseInt (args [1]); 
     System .out.println (args [i]); 
    } 
} 

What will happen when you compile and run the above program using the following command line:

java Main 1 2 

Select 1 option

  • A. It will print 1
  • B. It will print 2
  • C. It will print some junk value.
  • D. It will throw ArrayIndexOutOfBoundsException.
  • E. It will throw NumberFormatException


Correct Option is  : D

Note

Arrays are indexed from 0.

In java, the name of the class is not the first element of args.

When the command line is: java Main 1 2, args [0] is 1 and args [1] is 2.

When you try to access args [2], It will throw an ArrayIndexOutofBoundsException because the array length is only 2 so args [2] is out of bounds.




PreviousNext

Related