Java Command Line Arguments

Command line arguments are the arguments that are passed at run time to the Java program. Arguments are used as input for the program. There is no limit on the number of command line arguments that can be passed to the program.

Command line arguments are string by default because they are received by the main method’s string type array.

Command line arguments Example

package com.w3schools360;

public class CommandLineArgumentsTest {
      public static void main(String args[]){
    	  int num1, num2;
          //check number of entered parameters.
          if (args.length > 0) {
               try {
                //You need to parse string values to integer
                 num1 = Integer.parseInt(args[0]);
                 num2 = Integer.parseInt(args[1]);
                  System.out.println("Sum of numbers (Passed as Args) = ");
                  System.out.println(num1 + num2);
               } catch (NumberFormatException e) {
                //Catch exception if any.
                  System.err.println("Arguments must be integers.");


Sum of numbers (Passed as Args) =

Another Command line argument Example

package com.w3schools360;

public class CommandLineArgumentsTest2 {
    public static void main(String args[]) {

        // check number of entered parameters.
        if (args.length > 0) {
            // print all entered values.
            for (int i = 0; i < args.length; i++) {
                System.out.println("Argument at " + i + "Position: " + args[i]);


Argument at 0 Position: 20
Argument at 1 Position: 30
Argument at 2 Position: 40

How to execute a command line argument program in Eclipse?


  • In the Package Explorer, right-click on your Java class like “CommandLineArgumentsTest”.
  • Hover over “Run As” and choose “Java Application.”
  • Go to the “Arguments” tab.
  • In the “Program Arguments” section, enter your command line arguments separated by spaces.
  • Click “Apply” and then “Run.”

How to read input from the command line in Java using Scanner?

The scanner class is used to read input from the command line. The scanner class is in java.util package. Scanner class has methods like nextInt(), nextFloat(), nextDouble(), etc. which read numeric data without any need of parsing using Integer.parseInt(), etc. These methods will throw an exception if you pass string or char type value.


package com.w3schools360;

import java.util.Scanner;

public class ReadInputUsingScannerTest {
    public static void main(String args[]){
    Scanner scanner = new Scanner(new InputStreamReader(;
    System.out.println("Enter name: ");  

    String name = scanner.nextLine();
    System.out.println("Enter age: ");  

    int age = scanner.nextInt(); 
    System.out.println("Entered name : " + name);
    System.out.println("Entered age : " + age);


Enter name: 
Enter age: 
Entered name : Roy
Entered age : 36