How to Take Array Input From the User in Java
Hard-coded arrays like {10, 20, 30} are fine for learning syntax, but real programs need to react to whatever the user actually types. This guide walks through exactly how to build a Java program that asks the user how many elements they want, then reads each value one at a time into a properly sized array — the single most common pattern in introductory Java assignments, coding interviews, and command-line utilities.
Why Dynamic Array Input Matters
Every array we’ve discussed so far in this series has had values baked directly into the source code.
That’s useful for learning syntax, but it’s not how real software works.
Real applications need to respond to unpredictable input: a user might want an array of 3 elements today and 300 tomorrow.
Learning to size and fill an array based on user input is the bridge between “toy examples” and genuinely interactive programs.
Setting Up the Scanner
Java’s Scanner class, found in java.util.Scanner, is the standard tool for reading input from the keyboard (System.in).
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
This single line creates a Scanner object wired to standard input, ready to read whatever the user types.
Asking for Array Size
Since Java arrays are fixed-size, you need to know the size before creating the array.
The standard pattern is to ask the user first.
System.out.print("Enter the size of the array: ");
int size = sc.nextInt();
nextInt() blocks execution and waits for the user to type an integer and press Enter, then parses that input and stores it in size.
Once you have the size, you can create the array.
int[] numbers = new int[size];
If the user enters 5, Java allocates exactly 5 integer slots on the heap, all initialized to 0 by default until filled.
Reading Each Element
With the array created, loop through it, reading one value per iteration.
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
numbers[i] = sc.nextInt();
}
If the user types:
10 20 30 40 50
(separated by spaces or newlines — Scanner handles both), the array becomes:
[10, 20, 30, 40, 50]
Printing the Entered Elements
Once filled, you can confirm what was entered using an enhanced for loop.
System.out.println("You entered:");
for (int num : numbers) {
System.out.println(num);
}
Output
You entered:
10
20
30
40
50
Closing the Scanner (and Why It Matters)
Always close your Scanner object once you’re done reading input.
sc.close();
This releases the underlying input resource.
While it’s not always catastrophic to skip this in a short-lived console app, it’s a bad habit that becomes a real problem in larger applications where resources need to be managed carefully — and most static analysis tools and code reviewers will flag a missing close() call.
Full Working Program
import java.util.Scanner;
public class ArrayInputFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = sc.nextInt();
int[] numbers = new int[size];
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
numbers[i] = sc.nextInt();
}
System.out.println("You entered:");
for (int num : numbers) {
System.out.println(num);
}
sc.close();
}
}
Internal Working (Memory View)
When size is entered as 5, new int[size] allocates a 5-slot array on the heap.
As the loop runs, Scanner.nextInt() reads from a buffered input stream, parses text into an int, and each value is written directly into the corresponding heap slot via:
numbers[i] = sc.nextInt();
The loop counter i, the size variable, and the sc reference variable live on the stack, inside the main method’s frame.
Real-Life Analogy
Think of registering guests for an event.
First, you ask the organizer how many seats to set up (the array size).
Then, one by one, you write down each guest’s name as they arrive (filling the array).
You can’t add extra seats once the room is set up — if you need more, you’d need to reorganize the whole room (create a new, bigger array).
Best Practices
- Always validate that the user-entered size is a positive number before creating the array, to avoid
NegativeArraySizeException. - Close the
Scannerwhen you’re finished reading input, ideally using try-with-resources in larger programs. - Use clear prompts (
System.out.print) so the user knows exactly what format of input is expected. - Consider wrapping
nextInt()calls in a try-catch forInputMismatchExceptionif users might enter non-numeric text.
Common Mistakes
Forgetting to Create the Array
Trying to fill the array before creating it leads to ArrayIndexOutOfBoundsException or a NullPointerException if it was declared but never initialized.
Mixing nextInt() and nextLine()
Without handling the leftover newline character, this classic Scanner gotcha causes skipped input.
Not Validating the Array Size
A negative or absurdly large number entered by the user can crash the program or exhaust memory.
Forgetting to Close the Scanner
This can leak resources in long-running or repeatedly invoked programs.
Assuming Input Is Always Valid
A non-numeric entry causes InputMismatchException if not handled.
Expert Tips
- For more robust, production-grade input handling, consider
BufferedReadercombined withInteger.parseInt()for greater control over parsing exceptions and performance with very large inputs. - If you need to accept space-separated input all on one line,
sc.nextLine().split(" ")combined with parsing into integers is a common alternative pattern. - Always wrap user-facing input logic in validation loops (
whileloops that re-prompt on invalid input) for production-quality command-line tools.
Alternative Input Methods
| Method | Pros | Cons |
|---|---|---|
| Scanner | Simple API, easy for beginners | Slightly slower for very large input volumes |
| BufferedReader + split() | Faster, more control | More verbose, manual parsing required |
Command-line arguments (args[]) |
No interactive prompt needed | Limited to values passed at program launch |
| Reading from a file | Good for large, repeatable datasets |
Requires file I/O handling and error checking
|
Frequently Asked Questions
Why do I need to ask for the array size before creating the array?
Because Java arrays are fixed-size — you must know the size at creation time; you can’t grow the array afterward.
What happens if the user enters a negative size?
Java throws a NegativeArraySizeException at runtime when you try to create the array.
Can I take array input on a single line instead of one number at a time?
Yes.
Read a full line with nextLine(), split it by spaces, then parse each value into an integer.
Why should I close the Scanner?
To release the input stream resource properly.
Leaving it open is a resource leak, especially in larger or long-running applications.
What if the user types letters instead of numbers?
nextInt() throws an InputMismatchException.
You should catch this exception and prompt the user to try again for production-quality code.
Is Scanner the only way to read array input in Java?
No.
BufferedReader, command-line arguments, and file-based input are all valid alternatives depending on your use case.
Can I use this same pattern for a 2D array?
Yes.
Simply nest the input loop, reading rows and columns based on two user-provided dimensions.
Does closing the Scanner also close System.in?
Yes.
Closing a Scanner wrapping System.in closes the underlying stream too, so avoid creating multiple Scanner objects on System.in in the same program.
Conclusion
Taking array input from the user is one of the most important beginner Java skills because it introduces dynamic programming instead of relying on hard-coded values.
The standard workflow is simple:
- Create a
Scanner. - Read the array size.
- Create the array.
- Read each element using a loop.
- Print the array.
- Close the
Scanner.