Home / Java Programming / Objects and Collections :: Discussion

Discussion :: Objects and Collections

  1. What will be the output of the program?

      public class Test
      {     
         public static void main (String[] args)  
         {        
            String foo = args[1];       
            String bar = args[2];        
            String baz = args[3];      
            System.out.println("baz = " + baz); /* Line 8 */     
       }  
    } 

     

    And the command line invocation:

    > java Test red green blue

     

     

  2. A.

    baz =

    B.

    baz = null

    C.

    baz = blue

    D.

    Runtime Exception

    View Answer

    Workspace

    Answer : Option D

    Explanation :

    When running the program you entered 3 arguments "red", "green" and "blue". When dealing with arrays in java you must remember ALL ARRAYS IN JAVA ARE ZERO BASED therefore args[0] becomes "red", args[1] becomes "green" and args[2] becomes "blue".

    When the program entcounters line 8 above at runtime it looks for args[3] which has never been created therefore you get an

    ArrayIndexOutOfBoundsException at runtime.

     


Be The First To Comment