In Java, user input refers to the data or information provided by the user during the execution of a program. This input is usually taken through the console (command line) and can be used to perform various operations in your program. Java provides different ways to collect input, with the most common being the Scanner
class.
Syntax
- Import the
Scanner
class from thejava.util
package. - Create an object of the
Scanner
class. - Use methods like
nextLine()
,nextInt()
, ornextDouble()
to capture input.
User Input Methods (Scanner Class)
Method | Data Type | Description | Example |
---|---|---|---|
nextLine() |
String | Reads a full line of text input. | String name = scanner.nextLine(); |
next() |
String | Reads a single word (stops at space). | String word = scanner.next(); |
nextInt() |
int | Reads an integer input. | int age = scanner.nextInt(); |
nextDouble() |
double | Reads a decimal (floating-point) number. | double price = scanner.nextDouble(); |
nextFloat() |
float | Reads a floating-point number. | float weight = scanner.nextFloat(); |
nextLong() |
long | Reads a long integer. | long bigNumber = scanner.nextLong(); |
nextShort() |
short | Reads a short integer. | short smallNumber = scanner.nextShort(); |
nextByte() |
byte | Reads a byte value. | byte tinyNumber = scanner.nextByte(); |
nextBoolean() |
boolean | Reads a boolean (true or false ). |
boolean isJavaFun = scanner.nextBoolean(); |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Scanner; public class UserInputExample { public static void main(String[] args) { // Step 1: Create a Scanner object Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user for input System.out.println("Enter your name: "); String name = scanner.nextLine(); // Reads a line of text System.out.println("Enter your age: "); int age = scanner.nextInt(); // Reads an integer // Step 3: Output the user's input System.out.println("Hello " + name + ", you are " + age + " years old."); // Close the scanner scanner.close(); } } |