Java Programming - Objects and Collections - Discussion
Discussion Forum : Objects and Collections - Finding the output (Q.No. 1)
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
Answer: Option
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.
Discussion:
5 comments Page 1 of 1.
Ifanboi said:
7 years ago
@All.
Use ide like eclipse to give direct arguments. Put red green blue in arguments to use them as arguments.
Use ide like eclipse to give direct arguments. Put red green blue in arguments to use them as arguments.
Uwe said:
8 years ago
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?
Ranjit said:
10 years ago
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.
> javac Test.Java.
> java Test red green blue.
Or.
> java Test red green blue white.
Narmadha valli said:
10 years ago
When I run the program automatically I will get the error. Am not able to give inputs. Please give the solution.
Nagaraju revalla said:
1 decade ago
If I run as >java Test red green blue white.
Then what will happen?
Then what will happen?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers