JAVA COMMAND LINE ARGUMENT

Command Line Arguments in Java makes us to pass the arguments to the program while execution. In this module we will learn more about Java Command Line Arguments with examples. Before diving into command line arguments kindly have a look at Java Operators.

Table of Contents

[hide]
  • What is Java Command Line Argument ?
  • Command Line Argument Example

What is Java Command Line Argument ?

Java Command Line Argument excepts arguments at the time of executing a Java program. The argument which we will pass will be provided to the Java main function. String array in the main function accepts this arguements.

If you are not aware about java main method, just have a look at our Java-simple-program module where we have discussed the syntax of a simple java program.

You can pass any number of java command line arguments while executing a Java Program. These arguements are passed as strings to the java main method.

Steps to run a java program in command promt :

STEP 1 : Write a simple program that will receive two argument.
copyimage
// Java program to illustrate Java Command Line Argument.
public class CommandLineExample{
      public static void main(String args[]){  
          System.out.println("First argument is: " + args[0]);
          System.out.println("Second argument is: " + args[1]);
     }
}
STEP 2 : Compile and run the given program :
javac CommandLineExample.java // Compilejava CommandLineExample Codebator Tutorial // Run
STEP 3 :Finally you will get the output as below :
First argument is : Codebator Second argument is: Tutorial

Command Line Argument Example

Example

copyimage
// Java program to calculate sum of numbers
public class CommandLineExample{
      public static void main(String args[]){  
           int sum = 0;
           for( int i=0 ; i< args.length ; i++){
           sum = sum + Integer.parseInt(args[i]);
           }
           System.out.println("Sum is: " + sum);
     }
}

Compile and run the given program :

javac CommandLineExample.java // Compilejava CommandLineExample 20 40 60 // Run

OUTPUT

Sum is : 120

You can provide any number of inputs, in above program I have calculated the sum with three numbers, you can calculate the sum of n.. numbers. Hope you have got the basic understanding of Command Line Arguments in Java.