When we write Java programs, sometimes we don't want to provide all the values directly inside the code. Instead, we want the user to enter information while the program is running.
For example, imagine you're creating a student registration program. You may want to ask the user for:
-
Name
-
Age
-
Roll number
-
Marks
-
Whether the student is eligible or not
Java provides the Scanner class to make taking user input simple.
In this lesson, we'll learn how to use Scanner to take different types of input from the user, including integers, floating-point numbers, boolean values, and strings.
What is Scanner in Java?
Scanner is a class provided by Java that allows us to read input from different sources.
For beginner programs, the most common source is the keyboard.
To use Scanner, we first need to import it:
import java.util.Scanner;
Here:
-
javais the top-level package. -
utilis a package inside Java. -
Scanneris the class we want to use. -
importallows us to refer to theScannerclass in our program.
Important:
importdoes not copy the entireScanner.javasource code into your program. It tells the Java compiler which class we want to use without writing its fully qualified name every time.
Creating a Scanner Object
After importing the Scanner class, we need to create a Scanner object.
Scanner scan = new Scanner(System.in);
Let's break this statement down:
Scanner scan = new Scanner(System.in);
Scanner
This is the class type.
scan
This is the variable that refers to our Scanner object.
You can give it another valid variable name, for example:
Scanner sc = new Scanner(System.in);
or:
Scanner input = new Scanner(System.in);
new
The new keyword is used to create a new object.
System.in
System.in represents the standard input stream. In a normal console application, this is connected to the keyboard input.
So:
Scanner scan = new Scanner(System.in);
essentially gives us a Scanner object that can read input entered through the keyboard.
Taking Integer Input
If we want the user to enter an integer, we can use:
nextInt()
Example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your age:");
int age = scan.nextInt();
System.out.println("Your age is " + age);
scan.close();
}
}
If the user enters:
25
the output will be:
Your age is 25
Here:
int age = scan.nextInt();
takes the integer entered by the user and stores it in the age variable.
Taking Different Types of Input
The Scanner class provides different methods for reading different data types.
Integer
int number = scan.nextInt();
Byte
byte number = scan.nextByte();
Short
short number = scan.nextShort();
Long
long number = scan.nextLong();
Float
float number = scan.nextFloat();
Double
double number = scan.nextDouble();
Boolean
boolean value = scan.nextBoolean();
For example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: ");
int a = scan.nextInt();
System.out.print("Enter a decimal number: ");
double b = scan.nextDouble();
System.out.print("Are you a student? ");
boolean isStudent = scan.nextBoolean();
System.out.println("Integer: " + a);
System.out.println("Decimal: " + b);
System.out.println("Student: " + isStudent);
scan.close();
}
}
Taking String Input
When working with text, Scanner provides two commonly used methods:
next()
and:
nextLine()
Although both are used to read text, they behave differently.
next() in Java
The next() method reads one token, which normally means one word separated by whitespace.
For example:
System.out.print("Enter your name: ");
String name = scan.next();
If the user enters:
Rohan
the value stored in name will be:
Rohan
But suppose the user enters:
Rohan Kumar
next() will only read:
Rohan
It stops reading when it encounters whitespace.
nextLine() in Java
The nextLine() method reads the complete line, including spaces.
For example:
System.out.print("Enter your full name: ");
String name = scan.nextLine();
System.out.println("Hello " + name);
If the user enters:
Rohan Kumar
the complete value stored in name will be:
Rohan Kumar
Therefore:
next() → Reads one word/token
nextLine() → Reads the complete line
next() vs nextLine()
Consider the following example:
System.out.print("Enter your first name: ");
String firstName = scan.next();
System.out.print("Enter your full name: ");
String fullName = scan.nextLine();
The two methods behave differently.
| Method | What it reads |
|---|---|
next() |
One word/token |
nextLine() |
Complete line |
For example, if the input is:
Rohan Kumar
then:
scan.next();
reads:
Rohan
while:
scan.nextLine();
can read:
Rohan Kumar
Important Problem with nextInt() and nextLine()
Beginners often encounter a problem when using nextInt() followed by nextLine().
Consider:
System.out.print("Enter your age: ");
int age = scan.nextInt();
System.out.print("Enter your name: ");
String name = scan.nextLine();
You might expect nextLine() to wait for the name.
However, nextInt() reads the integer but leaves the newline character in the input buffer.
So nextLine() may consume that remaining newline instead of waiting for a new line of text.
A common solution is to call nextLine() once after nextInt():
System.out.print("Enter your age: ");
int age = scan.nextInt();
scan.nextLine();
System.out.print("Enter your name: ");
String name = scan.nextLine();
Now the program correctly waits for the name.
This is an important behavior to understand when mixing numeric input methods with nextLine().
Handling Invalid Input
What happens if our program expects an integer but the user enters something else?
For example:
int age = scan.nextInt();
Suppose the user enters:
twenty
The input cannot be converted into an integer, so Java throws an:
java.util.InputMismatchException
This happens because the type of input provided by the user doesn't match the type expected by the Scanner method.
For example:
int age = scan.nextInt();
expects an integer such as:
25
but not:
Hello
For beginner programs, it's important to understand that the Scanner method you're using determines what kind of input Java expects.
String Concatenation with User Input
Once we take input from the user, we can combine it with other strings using the + operator.
For example:
String name = "Rohan";
System.out.println("Hello " + name);
Output:
Hello Rohan
This is called String concatenation.
We can use the same concept with user input:
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Enter your age: ");
int age = scan.nextInt();
System.out.println(
"Your name is " + name + " and your age is " + age
);
scan.close();
If the user enters:
Rohan Kumar
25
the output will be:
Your name is Rohan Kumar and your age is 25
Real-World Example: Student Registration
Let's create a simple student registration program.
We can ask the user for their name, age, roll number, and percentage.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Enter your age: ");
int age = scan.nextInt();
System.out.print("Enter your roll number: ");
int rollNumber = scan.nextInt();
System.out.print("Enter your percentage: ");
double percentage = scan.nextDouble();
System.out.println("\n--- Student Details ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Percentage: " + percentage);
scan.close();
}
}
A possible interaction could look like:
Enter your name: Rohan Kumar
Enter your age: 22
Enter your roll number: 101
Enter your percentage: 85.5
--- Student Details ---
Name: Rohan Kumar
Age: 22
Roll Number: 101
Percentage: 85.5
Here, the program is no longer using fixed values. The user provides the information while the program is running.
Closing the Scanner
Once we have finished taking input, we can close the Scanner:
scan.close();
This releases the resource associated with the Scanner.
For a console application, closing the Scanner also closes the underlying System.in input stream.
After closing it, we should not try to use the same Scanner for more input.
For example:
scan.close();
int number = scan.nextInt();
will result in an exception because the Scanner has already been closed.
Therefore, close the Scanner when you are completely finished with user input.
Complete Example
Here is a simple program that demonstrates the main concepts covered in this lesson:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = scan.nextLine();
System.out.print("Enter your age: ");
int age = scan.nextInt();
System.out.print("Enter your percentage: ");
double percentage = scan.nextDouble();
System.out.print("Are you a student? ");
boolean isStudent = scan.nextBoolean();
System.out.println("\n--- Details ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Percentage: " + percentage);
System.out.println("Student: " + isStudent);
scan.close();
}
}
Key Takeaways
In this lesson, we learned how to take input from a user using the Scanner class.
The important points are:
-
Import the Scanner class:
import java.util.Scanner;
-
Create a Scanner object:
Scanner scan = new Scanner(System.in);
-
Use the appropriate method according to the required data type:
scan.nextInt();
scan.nextDouble();
scan.nextFloat();
scan.nextLong();
scan.nextBoolean();
-
Use
next()for a single token:
String name = scan.next();
-
Use
nextLine()to read a complete line:
String name = scan.nextLine();
-
Be careful when using
nextLine()immediately after methods such asnextInt()because the remaining newline can be consumed bynextLine(). -
If the user enters an incompatible type, methods such as
nextInt()can throwInputMismatchException. -
Close the Scanner when you have finished taking input:
scan.close();
With Scanner, our Java programs can interact with users instead of working only with values that are already written inside the source code. This is an important step toward building programs that respond to real user input.