Java Tutorial-Java User Input

Java User Input (Scanner)


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

To use the Scanner class in Java, we create an object for the class and use any of the methods in the class. In the below example, we use the nextLine() method , which is used to read the Strings:


Example

import java.util.Scanner; //import the Scanner class
 
public class ScannerClass {
       public static void main (String args[]){
              Scanner myObj = new Scanner(System.in); //Create a scanner object
              System.out.println("Enter best online training institute : ");
             
              String institute = myObj.nextLine();     //Read the user input
              System.out.println("Best online training institute : "+institute);   //Print user input
       }
}

Output

Enter best online training institute :
SparkDatabox
Best online training institute : SparkDatabox

Other Input Types

In the above example, we used nextLine() method to read Strings. To read the other types, we use the below methods:


Example


In the below example, we read three types of input such as String, int and double.

import java.util.Scanner; //import the Scanner class
 
public class ScannerClass {
       public static void main (String args[]){
              Scanner myObj = new Scanner(System.in); //Create a scanner object
              System.out.println("Enter name, age and salary : ");
             
              String name = myObj.nextLine();   //Read the String value
              int age = myObj.nextInt();  //Read the integer value
              double salary = myObj.nextDouble();  //Read the double value
             
              //Print user input
              System.out.println("Name : "+name);     
              System.out.println("Age : "+age);
              System.out.println("Salary : "+salary);
       }
}

Output

Enter name, age and salary :
John
30
1300000
Name : John
Age : 30
Salary : 1300000.0

Method

Description

nextBoolean()

Reads a boolean value from the user

nextByte()

Reads a byte value from the user

nextInt()

Reads a integer value from the user

nextFloat()

Reads a float value from the user

nextDouble()

Reads a double 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