Difference between using Scanner Class and String args for user input in Java


To read user input in a Java program we can use

1. String args[] : Command Line Arguments

These are command-line arguments that has to be passed when the Java program is run on command prompt/terminal.

java myProg Param1 Param2
$ java myProg Args1 Args2

args is an array of String values.

Example :
import java.util.Scanner;

public class stringArgsDemo {

public static void main(String[]arguments){

Scanner input = new Scanner(System.in);

    String name;
    int age;

 System.out.print("Enter First multiple");
        number1 = input.nextInt();

      //This is not a interactive way!
        name =  args[0];
        age =  Integer.parseInt(args[1]);

       System.out.println("Name : "+name +"\n" +"Age : "+age);
   }

}

2. Scanner : Standard Input

This is a interactive way of accepting inputs from the user. When ever input.nextInt(), input.next() is encountered the prompt stops to get input from the user.

Example :

import java.util.Scanner;

public class scannerClassDemo {

public static void main(String[]arguments){

Scanner input = new Scanner(System.in);

    String name;
    int age;

 System.out.print("Enter First multiple");
        number1 = input.nextInt();

       //Interactive way of getting input
        System.out.printlin ("Enter your Name : ");
        name = input. next();

        System.out.printlin ("Enter your Age : ");
        age = input. nextInt();

       System.out.println("Name : "+name +"\n" +"Age : "+age);
   }

}