Command-Line Arguments to Main

Command-Line Arguments to Main

Command Line Argument is working similar as all other arrays. The main method is called firstly one the JVM invokes , it must be take a String array parameter.

class TestMain {
public static void main (String [] args) {
System.out.println(\"First arg is \" + args[0]);

When we invoked command line :
%java TestMain Hello
output : First arg is Hello

main imp thing must be in mind when we use the command line argument .

  1. The length of the args array will always be equal to the number of command-line arguments.
  2. args.length is one, meaning there is one element in the array, and it is at index zero.
  3. length-1, you\'ll get an ArrayIndexOutOfBoundsException.

The following code is an example of a main method expecting three arguments :

public static void main (String [] args) {
if (args.length < 3) {
System.out.println(\"Usage: [name] [social security #]
//[IQ] Try again when you have a clue\");

Date:2024-02-09 00:00:00

Post Your Answers

User Email:

User Name:

Related SCJP1.5 chap1 Links

SCJP1.5 chap1 interview questions and answers for experienced and fresher