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 1 of 3.

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

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.

Sundar said:   1 decade ago
Hi Friends,

The array index always starts with '0' that means args[0].

C\:>java CommandArgs 1 2 3 4

The arguments variable 'args' will hold the elements as given below.

args[0] = 1
args[1] = 2
args[2] = 3
args[3] = 4

But in the program we are trying to get the element at 4th index.

String s4 = args[4]; // due to this line an exception is thrown.

I hope that you are all understand this. Have a nice day!

Mahesh said:   1 decade ago
Thanks Sundar.

Prathyusha said:   1 decade ago
Good explanation sundar!..

Anbu said:   1 decade ago
Good explanation mate !

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.

Srieeta Guptaj said:   1 decade ago
Very nice said. The answer is very clear to me. Thank you.

Jyothi said:   1 decade ago
But
args[0]=CommandArgs
i.e the program name know??


Post your comments here:

Your comments will be displayed after verification.