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


To read user input in a Java program we can use the,

1. String args[] : Command Line Arguments

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

$ java myProg Args1 Args2

String args is an array of String values. In the above example Arg1 = args 0 element, Args2 = args 1 element of the String[] array,

Code Example:
import java.util.Scanner;

public class stringArgsDemo {

public static void main(String[]arguments){

//Java Scanner String Input
Scanner input = new Scanner(System.in);

    String name;
    int age;

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

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

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

}

2. Scanner : Standard Input

Use Scanner Class in Java as an interactive way of accepting inputs from the user. Whenever input.nextInt(), input.next() is encountered the prompt stops to get input from the user.

Code Example:

import java.util.Scanner;

public class scannerClassDemo {

public static void main(String[]arguments){

//java scanner input
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);
   }

}


















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap