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);
   }

}
Advertisements
Try Out Code2care Dev Tools:

Advertisements



Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Advertisements


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency