Java OCA OCP Practice Question 3227

Question

Which main() method will succeed in printing the last program argument to the standard output and exit gracefully with no output if no program arguments are specified?.

Select the one correct answer.

(a) public static void main(String[] args) {
      if (args.length != 0)
        System.out.println(args[args.length-1]);
    }/*  w  w w.  ja v  a  2  s .c o m*/
(b) public static void main(String[] args) {
      try { System.out.println(args[args.length]); }
      catch (ArrayIndexOutOfBoundsException e) {}
    }
(c) public static void main(String[] args) {
      int ix = args.length;
      String last = args[ix];
      if (ix != 0) System.out.println(last);
    }
(d) public static void main(String[] args) {
      int ix = args.length-1;
      if (ix > 0) System.out.println(args[ix]);
    }
(e) public static void main(String[] args) {
      try { System.out.println(args[args.length-1]); }
      catch (NullPointerException e) {}
    }


(a)

Note

The main() method in (b) will always generate and catch an ArrayIndexOutOfBoundsException, since args.length is an illegal index in the args array.

The main() method in (c) will always throw an ArrayIndexOutOfBoundsException since it is also uses args.length as an index, but this exception is never caught.

The main() method in (d) will fail to print the argument if only one program argument is supplied.

The main() method in (e) will generate an uncaught ArrayIndexOutOfBoundsException if no program arguments are specified.




PreviousNext

Related