User Input In Java

User Input (Scanner Class)

  1. Accepting values from user at program run time or from the command line.
  2. There are multiple option to accept input from user.
    1. Command Line Argument.
      1. Is use to pass user value at the time of providing execution command.
      2. These values will be capture inside the String array parameter of main method.
      3. All the values pass by user will be in String format.
    2. Buffer classes.
    3. Scanner Class.
    4. Console.

Scanner Class

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

Input Types

In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:

nextBoolean()Reads a boolean value from the user
nextByte()Reads a byte value from the user
nextDouble()Reads a double value from the user
nextFloat()Reads a float value from the user
nextInt()Reads a int value from the user
nextLine()Reads a String value from the user
nextLong()Reads a long value from the user
nextShort()Reads a short value from the user

Example :-

import java.util.*;  
class UserInputDemo   
   public static void main(String[] args)  {  
      Scanner sc= new Scanner(;    // is a standard input stream  
      System.out.print("Enter first number- ");  
      int a= sc.nextInt();  
      System.out.print("Enter second number- ");  
      int b= sc.nextInt();  
      System.out.print("Enter third number- ");  
      int c= sc.nextInt();  
      int d=a+b+c;  
      System.out.println("Total= " +d);  

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(;

    System.out.println("Enter name, age and salary:");

    // String input
    String name = myObj.nextLine();

    // Numerical input
    int age = myObj.nextInt();
    double salary = myObj.nextDouble();

    // Output input by user
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("Salary: " + salary);



Join Telegram : Click Here


All Full Stack Java Study Material


Programing Lang


Job’s For Fresher


Share This Information To Your Friends and Your College Group’s, To Help Them !