JavaUser Input (Scanner)
Java User Input
TheScanner class is used to get user input, and it is found in thejava.util package.
To use theScanner class, create an object of the class and use any of the available methods found in theScanner class documentation. In our example, we will use thenextLine() method, which is used to read Strings:
Example
import java.util.Scanner; // Import the Scanner classclass Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input }}If you don't know what a package is, read ourJava Packages Tutorial.
Input Types
In the example above, we used thenextLine() method, which is used to read Strings. To read other types, look at the table below:
| Method | Description |
|---|---|
nextBoolean() | Reads aboolean value from the user |
nextByte() | Reads abyte value from the user |
nextDouble() | Reads adouble value from the user |
nextFloat() | Reads afloat value from the user |
nextInt() | Reads aint value from the user |
nextLine() | Reads aString value from the user |
nextLong() | Reads along value from the user |
nextShort() | Reads ashort value from the user |
In the example below, we use different methods to read data of various types:
Example
import java.util.Scanner;class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); 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); }}Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like "InputMismatchException").
You can read more about exceptions and how to handle errors in theExceptions chapter.
Complete Scanner Reference
Tip: For a complete reference of Scanner methods, go to ourJava Scanner Reference.

