Java Programming - Objects and Collections - Discussion

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

[A]. baz =
[B]. baz = null
[C]. baz = blue
[D]. Runtime Exception

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.


Nagaraju Revalla said: (May 10, 2013)  
If I run as >java Test red green blue white.

Then what will happen?

Narmadha Valli said: (Oct 3, 2015)  
When I run the program automatically I will get the error. Am not able to give inputs. Please give the solution.

Ranjit said: (Dec 5, 2015)  
If you try to run this program on EditPlus you can't give input, try to run on CMD prompt.

> javac Test.Java.

> java Test red green blue.

Or.

> java Test red green blue white.

Uwe said: (Mar 10, 2017)  
For my understanding it seems that the user enters the following: java Test red green blue, means 5 Strings, not 3. How do I understand that only red green blue is meant as an input?

Ifanboi said: (Oct 6, 2018)  
@All.

Use ide like eclipse to give direct arguments. Put red green blue in arguments to use them as arguments.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.