C
C
Core Java
Search…
--> Java User Input (Scanner)

Java User Input

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:

Example

1
import java.util.Scanner; // Import the Scanner class
2
3
class MyClass {
4
public static void main(String[] args) {
5
Scanner myObj = new Scanner(System.in); // Create a Scanner object
6
System.out.println("Enter username");
7
8
String userName = myObj.nextLine(); // Read user input
9
System.out.println("Username is: " + userName); // Output user input
10
}
11
}
Copied!

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:
Method
Description
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
In the example below, we use different methods to read data of various types:

Example

1
import java.util.Scanner;
2
3
class MyClass {
4
public static void main(String[] args) {
5
Scanner myObj = new Scanner(System.in);
6
7
System.out.println("Enter name, age and salary");
8
9
// String input
10
String name = myObj.nextLine();
11
12
// Numerical input
13
int age = myObj.nextInt();
14
double salary = myObj.nextDouble();
15
16
// Output input by user
17
System.out.println("Name: " + name);
18
System.out.println("Age: " + age);
19
System.out.println("Salary: " + salary);
20
}
21
}
Copied!
Last modified 2yr ago