How to Take Multiple String Input in Java Using Scanner: A Step-by-Step Guide
By Rohan Vats
Updated on Jun 23, 2025 | 32 min read | 30.83K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Jun 23, 2025 | 32 min read | 30.83K+ 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 handle multiple string input in Java using Scanner, use methods like next(), nextLine(), and next() for capturing tokens or full lines. These methods allow you to handle space-separated tokens or multi-line entries efficiently.
By using these techniques, you can manage varied input types based on your program's needs. The Scanner class Java provides the flexibility needed for effective user interaction and input processing.
In this blog, you will learn how to take multiple string input in Java using Scanner. We’ll explore key methods like nextLine() and next() and how to handle edge cases.
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.
Also Read: Top 13 String Functions in Java | Java String [With Examples]
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. |
Bring your Java projects to life with object-oriented skills. Learn how to work with classes, objects, inheritance, and more. Enroll in the free Java Object-Oriented Programming course today and start building cleaner, smarter Java applications.
Now, let’s explore the 7-step process to efficiently handle multiple string input in Java using Scanner.
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.
Sample Code:
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.
Sample Code:
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.
Sample Code:
System.out.println(
Output:
Enter your name:
Output Explanation:
The output displays the prompt message, instructing the user on what input is required. It ensures the user understands what type of data to enter, preventing input inconsistencies.
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:
Sample Code:
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.
Output Explanation:
The output first shows the word "Apple" entered by the user, captured by scanner.next(). Then, it displays the full sentence "This is a test sentence." entered through scanner.nextLine(), ensuring both word and sentence inputs are correctly captured.
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.
Sample Code:
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.
Sample Code:
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.
Sample code:
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++
Output Explanation:
The program uses scanner.next() to capture space-separated words from the user input, one at a time. Each word is stored in a separate variable, ensuring precise handling of individual tokens, which are then displayed in the output.
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.
Sample Code:
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
Output Explanation:
The output shows each string entered by the user, starting with "Apple." It then displays "Banana" and "Cherry" after each input. This confirms the program captures and displays all entered strings sequentially.
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:
Sample Code:
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
Output Explanation:
The output shows the two integers "10" and "20" entered by the user. These integers are captured using scanner.nextInt() and displayed in the format "You entered: 10 and 20." This ensures that space-separated inputs are correctly processed and displayed.
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.
Sample Code:
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
Output Explanation:
The output shows the name "John Doe" entered by the user, captured with scanner.nextLine(). It then displays the age "25," captured using scanner.nextInt(), in the format "Name: Ram Pradhan, Age: 25." This confirms that both string and integer inputs are processed correctly.
Best Practices:
Use hasNext() with conditionals to continuously read inputs until a termination keyword (e.g., “done”) is typed.
Sample Code:
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
Output Explanation:
The output displays each valid number entered, such as "10," "20," and "30," followed by "You entered: [number]." When "hello" is typed, the program prompts "Invalid input. Please enter a number or 'done'." The loop stops when the user types "done," ending the input sequence.
Best Practices:
Customize input separation, such as reading comma-separated values instead of space-separated ones.
Sample Code:
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:
Also read: How To Take Input From User in Java
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().
Code 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 address: ");
String address = scanner.nextLine();
System.out.println("Age: " + age);
System.out.println("Address: " + address);
scanner.close();
}
}
Output:
Age: 28
Address: 123, MG Road, Bangalore
Output Explanation:
The program reads the integer input for age using scanner.nextInt() and then consumes the leftover newline with scanner.nextLine(). This ensures that the nextLine() captures the full address input without skipping any user input.
Also Read: StringBuffer in Java: Master 15 Powerful Methods of the StringBuffer Class
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
Output Explanation:
The program uses a while loop to repeatedly prompt the user for a valid integer input. If the user enters an invalid input (like "abc"), an InputMismatchException is caught, and the program requests input again, ensuring error handling.
Also Read: Comprehensive Guide to Exception Handling in Java: Best Practices and Examples
Also read: For-Each Loop in Java [With Coding Examples]
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.
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
Output:
Config: server.port=8080
Config: db.user=admin
Config: db.pass=secret
Output Explanation:
The program reads the configuration file line by line using scanner.nextLine(), displaying each setting. This demonstrates how handling multiple string input in Java using Scanner can be applied to read and process configuration data for applications.
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 often process data files (CSV, TXT, JSON) containing multiple string entries. By parsing these strings into arrays or collections, you can efficiently manipulate the data, such as filtering or aggregating.
Handling multiple string input in Java using Scanner is crucial for parsing such data formats and ensuring accurate processing. This allows for scalable data management and analysis.
Code Example:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class FileInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<String> students = new ArrayList<>();
System.out.println("Enter student names separated by commas (e.g., Rahul, Priya, Anjali):");
String input = scanner.nextLine();
String[] studentArray = input.split(",\\s*");
for (String student : studentArray) {
students.add(student);
}
System.out.println("\nYou entered the following student names:");
for (String student : students) {
System.out.println(student);
}
scanner.close();
}
}
Output:
You entered the following student names:
Rahul
Priya
Anjali
Output Explanation:
The program reads a line of comma-separated student names using scanner.nextLine(). It splits the input into individual names and stores them in a list, demonstrating how to handle multiple string input in Java using Scanner for processing data efficiently.
3. Command-Line Utilities
Java programs can accept multiple string inputs as command arguments or during runtime, allowing dynamic behavior customization. Similar to how frameworks like Scala, Flask, or JavaScript handle dynamic inputs for web and application development, Java can process multiple strings effectively.
Using Scanner, you can manage and manipulate these inputs efficiently, enabling your Java application to respond flexibly to varying user commands. Handling multiple string input in Java using Scanner ensures seamless integration with other technologies while maintaining consistency in data processing.
Code Example:
import java.util.Scanner;
import java.util.HashSet;
public class CommandLineInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashSet<String> uniqueTasks = new HashSet<>();
System.out.println("Enter unique tasks separated by space (type 'exit' to finish):");
while (scanner.hasNext()) {
String input = scanner.next();
if (input.equalsIgnoreCase("exit")) {
break;
}
uniqueTasks.add(input);
}
System.out.println("\nYou entered the following unique tasks:");
for (String task : uniqueTasks) {
System.out.println(task);
}
scanner.close();
}
}
Output:
You entered the following unique tasks:
debugging
coding
testing
Code Explanation:
The program reads space-separated tasks using scanner.next(), adding them to a HashSet to ensure uniqueness. This showcases how to handle multiple string input in Java using Scanner, effectively processing user input while preserving unique entries.
4. Chatbots and Interactive Applications
Conversational interfaces process multiple string inputs from users to understand context and provide relevant responses. Much like how Go, C++, C#, and R handles user inputs for interactive applications, Java uses Scanner to manage user conversations efficiently.
Code Example:
import java.util.Scanner;
import java.util.ArrayList;
public class ChatbotInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> userMessages = new ArrayList<>();
System.out.println("Chatbot: How can I assist you today?");
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
break;
}
userMessages.add(input);
System.out.println("Chatbot: You mentioned: " + input);
}
System.out.println("\nChatbot conversation summary:");
for (String message : userMessages) {
System.out.println("User: " + message);
}
scanner.close();
}
}
Output:
Chatbot conversation summary:
User: I have a billing issue.
User: My account number is 12345.
User: I was charged twice.
Output Explanation:
The program reads multiple lines of input using scanner.nextLine(), storing each message in an ArrayList to track the conversation. This demonstrates handling multiple string input in Java using Scanner, similar to how different languages might manage user input for interactive chatbot applications.
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. Tools like Docker and Kubernetes are often used to containerize and orchestrate these processes, ensuring scalability and efficiency.
In machine learning pipelines, frameworks like PyTorch and TensorFlow can be used to process and analyze large volumes of data. Efficient handling of multiple string input in Java using Scanner plays a crucial role in extracting, transforming, and loading data across systems.
Code Example:
import java.util.Scanner;
import java.util.ArrayList;
public class ETLInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> dataRecords = new ArrayList<>();
System.out.println("Enter data records (type 'exit' to finish):");
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
break;
}
dataRecords.add(input);
}
System.out.println("\nProcessed Data Records:");
for (String record : dataRecords) {
System.out.println("Record: " + record);
}
scanner.close();
}
}
Output:
Processed Data Records:
Record: Name: John, Age: 30, Location: Mumbai
Record: Name: Priya, Age: 28, Location: Delhi
Record: Name: Anjali, Age: 25, Location: Bangalore
Output Explanation:
The program reads multiple data records from the user using scanner.nextLine(), storing each record in an ArrayList. This demonstrates how handling multiple string input in Java using Scanner can be applied to data migration and ETL processes.
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
Sample Code:
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
Sample Code:
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:
Also Read: Creating a Dynamic Array in Java
Effectively managing multiple string inputs in Java improves program reliability and enhances the overall user experience. Beyond the basics, here are some practical techniques to help you handle various input scenarios more efficiently:
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:
Sample Code:
String line = scanner.nextLine();
String[] words = line.split("\\s+");
Output:
Enter words separated by spaces:
Mumbai Delhi Bangalore
You entered: Mumbai
You entered: Delhi
You entered: Bangalore
Output Explanation:
The program reads a line of space-separated city names like "Mumbai Delhi Bangalore" using scanner.nextLine(). It then splits the input and displays each city with "You entered:", demonstrating efficient space-separated input handling in Java using Scanner.
2. Reading Until a Sentinel Value: Sometimes you want to keep reading strings until the user types a special word like "exit".
Sample Code:
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);
}
Output:
You entered: Apple
You entered: Banana
You entered: Cherry
Output Explanation:
The program keeps reading inputs until the user types "exit" and stores them in the inputs list. Each string entered is displayed with "You entered:" followed by the input, demonstrating how to handle multiple string input in Java using Scanner.
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.
Learning multiple string input in Java using Scanner is essential for developing efficient, scalable applications that handle diverse user data. By using Scanner’s methods, you ensure accurate parsing and prevent input errors, crucial for system reliability. Implementing precise input management with Scanner enhances the effectiveness of your Java programs, especially in data-driven and interactive applications.
If you're looking to deepen your Java expertise and close any learning gaps, upGrad’s Software Development courses provide hands-on projects, personalized mentorship, and 1:1 guidance.
Here are some additional courses to support your continued growth in Java development.
If you're struggling to move beyond the basics or are unsure how to apply Java in real projects, upGrad can help. Our personalized counseling and hands-on courses are designed to guide you from fundamentals to advanced development with real-world relevance. You can also visit upGrad’s offline centers for in-person learning.
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