Java Programming - Language Fundamentals - Discussion

Discussion Forum : Language Fundamentals - Finding the output (Q.No. 2)
2.
What will be the output of the program?
public class CommandArgs 
{
    public static void main(String [] args) 
    {
        String s1 = args[1];
        String s2 = args[2];
        String s3 = args[3];
        String s4 = args[4];
        System.out.print(" args[2] = " + s2);
    }
}

and the command-line invocation is

> java CommandArgs 1 2 3 4

args[2] = 2
args[2] = 3
args[2] = null
An exception is thrown at runtime.
Answer: Option
Explanation:

An exception is thrown because in the code String s4 = args[4];, the array index (the fifth element) is out of bounds. The exception thrown is the cleverly named ArrayIndexOutOfBoundsException.

Discussion:
26 comments Page 2 of 3.

Kiran Gudivada said:   1 decade ago
Very nice explanation and I am searching for these type of questions so if you can possible post more. Thank you.

Praveenkumar said:   2 decades ago
Here in the code array size is not given. Then how it will be an exception of ArrayIndexOutOfBoundsException.

Arora said:   7 years ago
@Sundar,

argv[0] takes the class name, not the input variable. Please explain that how argv[0]=1?
(1)

Varsha said:   1 decade ago
@nikhila : Thanks for ur explanation abt Baldevs query .... even me too had the same doubt!

Vijaya said:   1 decade ago
@Nikhila.

I tried your code in eclipse but still getting array out of boundary exception.

Logaa said:   8 years ago
@Hardik Chavda.

Why it is displaying output only when java CommandArgs 1 2 3 4 is given?

Abiramibabu said:   8 years ago
I cannot understand how it process and get output as, An exception is thrown at runtime.
(3)

Hardik Chavda said:   9 years ago
@Balaji and @Vivek.

You should give arguments as shown below;
java CommandArgs 1 2 3 4

Ritesh said:   2 decades ago
So is it by default that a java program can have at the max 4 arguments?

Ananthraj said:   2 decades ago
I am very happy about I am a user of IndiaBIX. I need more explanation.


Post your comments here:

Your comments will be displayed after verification.