How to Take Multiple String Input in Java Using Scanner: A Step-by-Step Guide
By Rohan Vats
Updated on Jun 05, 2025 | 6 min read | 30.68K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Jun 05, 2025 | 6 min read | 30.68K+ views
Share:
Table of Contents
Did you know? Java has significantly improved its concurrency model by introducing virtual threads under Project Loom. Virtual threads are lightweight, allowing for handling a large number of concurrent tasks with minimal resource overhead, simplifying the development of high-performance applications. |
To take multiple string inputs in Java using the Scanner class, you can combine methods like next() and nextLine() depending on how input is structured—whether by words or full lines. This is critical in real-world tasks like processing form entries, reading commands, or handling chat inputs. Misusing these methods can lead to skipped inputs or unexpected behavior, especially due to how Scanner handles newline characters.
Knowing when and how to use each method is key to writing robust input-handling logic. This guide walks you through practical techniques, code examples, and common traps to help streamline string input collection in Java.
Multiple string input in Java refers to the process of reading more than one string value from the user during program execution. This is a common requirement in many applications where users provide lists, names, commands, or any series of textual data that the program needs to process.
Handling multiple strings efficiently allows developers to create interactive, user-friendly programs that can accept complex input without manual repetition. Java provides several ways to achieve this, most notably using the Scanner class, which simplifies reading strings from the console or other input sources.
Ready to deepen your understanding of critical tech skills and advance your career? Choose from our top-rated courses designed to elevate your technical skills and boost your career—enroll now and take the first step toward your success!
Multiple string input can be categorized mainly into two types based on how the data is provided by the user: reading multiple strings in one go and reading strings sequentially.
Understanding these approaches helps you pick the right input method and create a better user experience. Now let’s explore the importance of Multiple String below.
Handling multiple string input in Java effectively is essential for building interactive, reliable, and user-friendly Java applications. Whether your program is processing commands, collecting user data, or managing lists, capturing multiple strings accurately ensures the application functions as intended. Poor input handling can lead to unexpected bugs, data inconsistencies, or a frustrating user experience.
Java’s Scanner class offers versatile methods to read and process different types of string inputs. By using the right approach, you can ensure inputs are clean, validated, and formatted correctly. This is especially important in scenarios like form submissions, CLI tools, or text-based applications.
How does Scanner Enhance Multi-String Input Handling in Java?
Handling multiple string inputs with the Scanner class helps Java applications manage real-world user data more reliably, from parsing formats to preventing errors.
Here's how it solves common input challenges:
Challenge |
How Scanner & Input Handling Help |
User Input Variability | Handles inconsistent spacing, punctuation, and separators using methods like next() and nextLine(). |
Data Accuracy | Validates inputs to avoid empty or malformed entries, ensuring reliable data for forms or profiles. |
Input Formatting Expectations | Differentiates between formats (e.g., comma-separated vs. line-by-line) with clear prompts and logic. |
Single-Line vs. Multi-Line Input | Supports both token parsing (e.g., keywords) and iterative reading (e.g., lists) for flexible workflows. |
Error Prevention | Minimizes runtime errors by guiding users and processing inputs robustly and predictably. |
How Scanner Fits In
Input in Java using Scanner class is designed to simplify these tasks by offering flexible methods to read tokens (next()) or entire lines (nextLine()), allowing developers to tailor input handling according to the expected format. Its ability to parse different data types and work with custom delimiters makes it indispensable for robust multiple string input management.
By mastering multiple string input in Java using Scanner, you ensure your Java web applications can gracefully accept, validate, and process complex user input scenarios, enhancing both functionality and user experience.
Handling multiple string input in Java involves reading several strings from the user, either together or one after another. Managing this input efficiently is essential to building reliable console applications. The Scanner class is the standard Java utility that simplifies reading input from the console.
Before you can use Scanner, you must import it from java.util package. This is essential because Java organizes code into packages, and the Scanner class is part of the utility package. Without this import, your program won't recognize Scanner and will fail to compile.
import java.util.Scanner;
Output: No direct output; this step enables input reading functionality.
Tip: While Scanner is popular for its ease of use, alternatives like BufferedReader exist for more advanced input handling or better performance in large-scale applications.
Next, instantiate a Scanner object. This object acts as a bridge between your program and the input source, typically the console (keyboard), represented by System.in. Creating a single Scanner instance per input source is important to avoid resource conflicts or unexpected behavior.
Scanner scanner = new Scanner(System.in);
Output: No direct output; prepares your program to accept inputs.
Tip: Avoid creating multiple Scanner instances for the same input stream (System.in) as it can cause errors. Use one Scanner throughout your program and close it when you're done.
Clear and user-friendly prompts are vital. They inform the user exactly what is expected, reducing input errors and confusion. Always provide specific instructions on the kind of input you want and the format.
System.out.println(
Output:
Enter your name:
Tip: Without a clear prompt, users might enter data in unexpected formats, which can cause your program to misinterpret or reject inputs.
To read multiple strings, you can use the Scanner class with the next() or nextLine() methods, depending on the input format:
Code Example:
import java.util.Scanner;
public class StringInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first word:");
String word = scanner.next(); // Reads one word
scanner.nextLine(); // Consume leftover newline
System.out.println("Enter a full sentence:");
String sentence = scanner.nextLine(); // Reads full line
System.out.println("Word: " + word);
System.out.println("Sentence: " + sentence);
}
}
Sample Input:
Apple
This is a test sentence.
Sample Output:
Word: Apple
Sentence: This is a test sentence.
Tip: The string "Alice Johnson" is read using scanner.nextLine() and stored in the name variable. Although it isn't displayed right away, it's now available for any later processing.
Storing input is essential; without it, your program cannot use the data for logic, display, or further computation.
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
Once read, input values should be stored in variables or data structures like arrays or lists. This storage is necessary for later processing, validation, or output.
String name = scanner.nextLine()
Output: No direct output; stored data can be used further.
Tip: Without storing the input, your program cannot use the entered data for calculations, display, or logic decisions.
After completing input reading, close the Scanner to free system resources. This is good practice, especially in larger applications, to prevent resource leaks.
scanner.close();
Output: No output; a good practice to avoid resource leaks.
Tip: Closing the Scanner linked to System.in will also close the input stream, so avoid closing it if you plan further input operations in your program.
To solidify your understanding of handling multiple string input in Java, this section provides clear, hands-on code examples using the Scanner class. You’ll see how to effectively use both next() and nextLine() methods, along with loops, to read multiple inputs in various scenarios. These practical demonstrations will help you apply the concepts confidently in your own programs, ensuring accurate and efficient input processing.
Example 1: Using next() for Multiple Inputs
In this example, you will learn how to use the next() method of the Scanner class to read multiple strings one by one. The next() method reads input token by token, stopping at whitespace, making it ideal for capturing individual words entered sequentially.
The example demonstrates how to loop through inputs and process each string efficiently.
import java.util.Scanner;
public class ExampleNext {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter three words separated by spaces:");
String first = scanner.next();
String second = scanner.next();
String third = scanner.next();
System.out.println("Words entered: " + first + ", " + second + ", " + third);
scanner.close();
}
}
Input:
Java Python C++
Output:
Words entered: Java, Python, C++
Example 2: Using nextLine() with Loop
This example shows how to use the nextLine() method inside a loop to read multiple lines of input from the user. Unlike next(), which reads token by token, nextLine() captures the entire line, including spaces, making it suitable for inputs like sentences or paragraphs.
Using a loop allows you to continuously accept input until a specific condition is met such as entering a blank line or a sentinel value.
import java.util.Scanner;
public class ExampleNextLine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many strings will you enter?");
int n = scanner.nextInt();
scanner.nextLine(); // Consume newline
for (int i = 0; i < n; i++) {
System.out.println("Enter string " + (i + 1) + ":");
String input = scanner.nextLine();
System.out.println("You entered: " + input);
}
scanner.close();
}
}
3
Apple
Banana
Cherry
Output:
You entered: Apple
You entered: Banana
You entered: Cherry
These seven steps and examples provide a practical and clear way to handle multiple string input in Java using Scanner, ensuring your program captures and processes user input reliably.
Also Read: How to get User Input In Java [With Examples]
Now that you understand the fundamental steps to handle multiple string inputs using Scanner, let’s explore the different methods available in Java to take multiple inputs effectively.
The Scanner class in Java provides several methods to facilitate this, enabling you to read different types of data such as strings, integers, and floating-point numbers from the console, whether you need to read multiple values entered on a single line or collect inputs sequentially over multiple lines. Scanner’s versatile methods like next(), nextLine(), and loop constructs make handling multiple inputs straightforward and reliable.
This section explores the key techniques and best practices for taking multiple inputs using Scanner, helping you write clean, effective, and user-friendly input handling code.
The next() method reads the next token until whitespace, making it ideal for inputs separated by spaces on the same line. For example, reading two integers typed together:
import java.util.Scanner;
public class NextExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two integers:");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered: " + num1 + " and " + num2);
scanner.close();
}
}
Sample Input:
10 20
Output:
You entered: 10 and 20
Best Practices:
nextLine() reads the whole line, including spaces, useful when inputs come one per line or contain spaces. Example: reading a string and an integer on different lines.
import java.util.Scanner;
public class NextLineExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String name = scanner.nextLine();
System.out.println("Enter your age:");
int age = scanner.nextInt();
System.out.println("Name: " + name + ", Age: " + age);
scanner.close();
}
}
Sample Input:
John Doe
25
Output:
Name: John Doe, Age: 25
Best Practices:
Use hasNext() with conditionals to continuously read inputs until a termination keyword (e.g., “done”) is typed.
import java.util.Scanner;
public class LoopInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers (type 'done' to finish):");
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} else if (scanner.next().equalsIgnoreCase("done")) {
break;
} else {
System.out.println("Invalid input. Please enter a number or 'done'.");
}
}
scanner.close();
}
}
Sample Input:
10
20
hello
30
done
Output:
You entered: 10
You entered: 20
Invalid input. Please enter a number or 'done'.
You entered: 30
Best Practices:
Customize input separation, such as reading comma-separated values instead of space-separated ones.
import java.util.Scanner;
public class CustomDelimiterExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter comma-separated values (e.g., 10,20,30):");
scanner.useDelimiter(",");
while (scanner.hasNextInt()) {
int value = scanner.nextInt();
System.out.println("Value: " + value);
}
scanner.close();
}
}
Sample Input:
10,20,30
Output:
Value: 10
Value: 20
Value: 30
Explanation:
Important: Once set, a custom delimiter remains active for that Scanner instance. If you need to switch back to space or newline separation later, you must manually reset the delimiter using scanner.useDelimiter("\\s+").
Best Practices:
Now that you’re familiar with the different methods to take multiple string inputs using Scanner, it’s important to understand common pitfalls that can occur during input.
Handling multiple string inputs in Java using the Scanner class can sometimes lead to unexpected behavior and subtle bugs, especially for beginners. Common issues such as input skipping, buffer management, and invalid user inputs can make programs unreliable or confusing to use. Understanding these pitfalls and applying effective solutions is crucial for building robust console applications.
This section covers the most frequent challenges you’ll face with Scanner input, explains why they occur, and provides practical, code-backed solutions to help you avoid them.
1. Mixing next() and nextLine() Causing Input Skips
The methods next() and nextInt() read input tokens or numbers but do not consume the trailing newline character (\n) when you press Enter. However, nextLine() reads input until it encounters a newline character. This discrepancy causes a common pitfall: if you call nextLine() immediately after next() or nextInt(), it reads the leftover newline from the buffer rather than waiting for new input, resulting in an input skip.
Why this matters: This leads to bugs where your program seemingly skips user input without giving the user a chance to enter data, breaking the expected flow.
Solution: Always add an extra scanner.nextLine() after calling next(), nextInt(), or similar methods to consume and discard the leftover newline before using nextLine().
Example:
import java.util.Scanner;
public class InputSkipExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume leftover newline
System.out.print("Enter your full name: ");
String name = scanner.nextLine();
System.out.println("Age: " + age);
System.out.println("Name: " + name);
scanner.close();
}
}
Sample Input:
25
John Doe
Output:
Enter your age: 25
Enter your full name: John Doe
Age: 25
Name: John Doe
2. Troubleshooting Tip: Scanner Skipping Input?
If nextLine() seems to skip input after nextInt() or next(), it’s likely due to a leftover newline character in the buffer.
Refer to Step 4: Read and Handle Multiple String Inputs for a full explanation and fix using scanner.nextLine() to clear the buffer before reading lines.
3. Input Validation and Error Handling
Users may enter data that doesn’t match the expected type (e.g., typing letters when a number is requested), which leads to exceptions like InputMismatchException. Without validation, your program can crash or behave unpredictably.
Why this matters: Robust programs must gracefully handle unexpected or invalid inputs to maintain stability and provide a good user experience.
Solution: Use try-catch in Java to catch exceptions and loops to prompt users repeatedly until valid input is received.
Example:
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputValidationExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
boolean valid = false;
while (!valid) {
System.out.print("Enter a valid integer: ");
try {
number = scanner.nextInt();
valid = true;
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter an integer.");
scanner.nextLine(); // Clear invalid input
}
}
System.out.println("You entered: " + number);
scanner.close();
}
}
Sample Input/Output:
Enter a valid integer: abc
Invalid input! Please enter an integer.
Enter a valid integer: 42
You entered: 42
Additional Solutions and Best Practices
Now that you’ve learned how to handle multiple string inputs with Scanner, let’s look at where these techniques apply in real-world scenarios.
Handling multiple string inputs efficiently is a common requirement in Java programming. Whether you're developing user-facing applications, processing large datasets, or building command-line tools, capturing and managing multiple strings in an organized way is essential.
Below, you will explore practical scenarios where multiple string inputs become vital, followed by code examples demonstrating how to read and store these inputs into appropriate data structures.
Practical Use Cases for Multiple String Input
Handling multiple string input isn’t just a console exercise; it plays a key role in real-world Java applications where structured or user-driven text input is essential.
Here are some practical scenarios where these techniques directly apply.
1. Reading Configuration Files or Properties
In backend applications or system tools, configuration files often contain key-value pairs in plain text. Reading these lines as strings and parsing them correctly is essential for setting up environments or customizing behavior dynamically.
Example: Reading application settings from a config file
server.port=8080
db.user=admin
db.pass=secret
Each line is read as a string and split using a delimiter (=), then stored in a map or similar structure for quick access. This technique is widely used in loading .properties files or environment settings during app initialization.
2. Data Parsing from Files or Streams: Applications frequently read data files (CSV, TXT, JSON) containing multiple string entries. Parsing these strings into arrays or collections enables data manipulation like filtering or aggregation.
Example: A CSV file storing customer data might look like:
John Doe,johndoe@example.com,New York
Jane Smith,janesmith@example.com,California
Parsing this file line by line into a List<String[]> allows you to access each customer’s name, email, and location as separate strings for analysis or reporting.
3. Command-Line Utilities: CLI Java programs accept multiple string inputs as command arguments or during runtime to define behavior dynamically.
Example: A file search utility might accept multiple keywords as input:
java SearchTool keyword1 keyword2 keyword3
These keywords are stored in an array or list and used to filter files containing any of these terms.
4. Chatbots and Interactive Applications: Conversational interfaces process multiple string inputs from users to understand context and provide relevant responses.
Example: A customer support chatbot may collect multiple user inputs in sequence:
Storing these inputs helps the chatbot track the conversation and escalate or resolve issues.
5. Data Migration and ETL Processes: During data migration or ETL (Extract, Transform, Load) operations, applications extract multiple strings, clean or transform them, and then load them into target systems.
Example: Migrating user profiles from an old system involves extracting multiple string fields such as username, email, address, and phone number, cleaning inconsistencies (like trimming spaces or fixing formats), and loading them into a new database.
Java Code Examples: Reading Multiple Strings into Arrays and Lists
To demonstrate how you can read multiple strings from user input and store them, we'll use two common approaches:
Both methods use a Scanner for input reading.
1. Reading Multiple Strings into an Array
import java.util.Scanner;
public class MultipleStringInputArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of strings you want to input: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume leftover newline
String[] inputs = new String[n];
System.out.println("Enter " + n + " strings:");
for (int i = 0; i < n; i++) {
inputs[i] = scanner.nextLine();
}
System.out.println("\nYou entered:");
for (String s : inputs) {
System.out.println(s);
}
scanner.close();
}
}
Sample Input:
Enter number of strings you want to input: 3
Enter 3 strings:
Java
Python
C++
Sample Output:
You entered:
Java
Python
C++
Explanation:
2. Reading Multiple Strings into an ArrayList
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MultipleStringInputList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of strings you want to input: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume newline
List<String> stringList = new ArrayList<>();
System.out.println("Enter " + n + " strings:");
for (int i = 0; i < n; i++) {
String input = scanner.nextLine();
stringList.add(input);
}
System.out.println("\nYou entered:");
for (String s : stringList) {
System.out.println(s);
}
scanner.close();
}
}
Sample Input:
Enter number of strings you want to input: 4
Enter 4 strings:
Apple
Banana
Cherry
Date
Sample Output:
You entered:
Apple
Banana
Cherry
Date
Explanation:
Additional Tip for Handling Multiple String Inputs
1. Using Space-Separated Input: You can read multiple strings from a single line separated by spaces using scanner.nextLine() and then splitting by space:
String line = scanner.nextLine();
String[] words = line.split("\\s+");
2. Reading Until a Sentinel Value: Sometimes you want to keep reading strings until the user types a special word like "exit".
List<String> inputs = new ArrayList<>();
String input;
System.out.println("Enter strings (type 'exit' to stop):");
while (!(input = scanner.nextLine()).equalsIgnoreCase("exit")) {
inputs.add(input);
}
3. Validating Inputs: Add validation to ensure inputs meet criteria such as length, format, or forbidden characters.
Also Read: Common String Functions in C with Examples
With a clear grasp of when and how to handle multiple string inputs in Java, you're ready to build better programs. Next, consider sharpening your skills through quality learning.
Mastering the handling of multiple string inputs significantly boosts your Java programming proficiency. It strengthens your ability to manage user data, process files, and build dynamic applications that respond to real-world demands. These skills form the foundation for working with more advanced Java concepts like collections, file input/output (I/O), and data processing.
To continue growing your expertise, consider diving deeper into the Collection Framework in Java to efficiently store and manipulate groups of objects, or explore File I/O to read from and write to files, which are key skills for building scalable, data-driven applications.
If you’re eager to expand your Java knowledge further, upGrad offers a wide range of tutorials and courses to take you from fundamentals to advanced programming. Below are some of the courses that you can opt for to upskill.
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
References:
https://medium.com/javarevisited/java-features-in-2025-9177290e7923
https://sourcebae.com/blog/how-to-take-multiple-string-input-in-java-using-scanner/
https://coderanch.com/t/755902/java/Scanner-class-read-multiple-lines
408 articles published
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources