To get user input in Java, we can use the Scanner class, which is part of the java.util package.
The Scanner class has many methods for reading input of various types.
Scanner ClassTo use the Scanner class, you must first import it and then create an object of the class.
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 } }
Note: Interactive user input does not work in the simple code editor on this page. You would need to run this code in a local development environment or a more advanced online IDE to test it properly.
In the example above, we used the nextLine() method, which is used to read String values. To read other types, you can use the appropriate method:
| 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 an 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 |
Scanner myObj = new Scanner(System.in);System.out.println("Enter name, age and salary:"); String name = myObj.nextLine(); // Reads string int age = myObj.nextInt(); // Reads integer double salary = myObj.nextDouble(); // Reads double
System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary);