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.


Advertisement

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 Scanner when 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 for InputMismatchException if 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 BufferedReader combined with Integer.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 (while loops 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

 

Make It Testable: Read From Any Scanner

A main method that reads from the keyboard can't be tested automatically. Move the logic into a method that takes a Scanner — in the program it reads System.in, in a test it reads a string:

import java.util.Scanner;

public class ArrayReader {

    /** Reads a size followed by that many integers. Throws on invalid or missing input. */
    public static int[] readArray(Scanner sc) {
        int size = sc.nextInt();
        if (size < 0) {
            throw new IllegalArgumentException("Size must be 0 or more, got " + size);
        }
        int[] numbers = new int[size];
        for (int i = 0; i < size; i++) {
            numbers[i] = sc.nextInt();
        }
        return numbers;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size, then the elements: ");
        int[] numbers = readArray(sc);
        System.out.println("You entered: " + java.util.Arrays.toString(numbers));
    }
}

Now TestNG can "type" any input, including the awkward cases:

import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ArrayReaderTest {

    @DataProvider(name = "validInput")
    public Object[][] validInput() {
        return new Object[][] {
            { "5 10 20 30 40 50", new int[]{10, 20, 30, 40, 50} },
            { "3\n7\n8\n9",       new int[]{7, 8, 9} },          // one value per line
            { "  2   -4   0  ",   new int[]{-4, 0} },            // extra spaces, negatives
            { "0",                new int[]{} },                  // empty array
        };
    }

    @Test(dataProvider = "validInput")
    public void readsWhatTheUserTyped(String typed, int[] expected) {
        Assert.assertEquals(ArrayReader.readArray(new Scanner(typed)), expected);
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void rejectsNegativeSize() {
        ArrayReader.readArray(new Scanner("-3"));
    }

    @Test(expectedExceptions = InputMismatchException.class)
    public void rejectsTextInsteadOfNumbers() {
        ArrayReader.readArray(new Scanner("3 10 ten 30"));
    }

    @Test(expectedExceptions = NoSuchElementException.class)
    public void failsWhenFewerValuesThanSize() {
        ArrayReader.readArray(new Scanner("4 1 2"));
    }
}

Result:

PASS failsWhenFewerValuesThanSize -> NoSuchElementException
PASS readsWhatTheUserTyped[5 10 20 30 40 50, [10, 20, 30, 40, 50]]
PASS readsWhatTheUserTyped[3\n7\n8\n9, [7, 8, 9]]
PASS readsWhatTheUserTyped[  2   -4   0  , [-4, 0]]
PASS readsWhatTheUserTyped[0, []]
PASS rejectsNegativeSize -> IllegalArgumentException
PASS rejectsTextInsteadOfNumbers -> InputMismatchException
Total: 7, Passed: 7, Failed: 0

We compiled these tests with Java 21 and ran them with a minimal TestNG-compatible runner (the full TestNG library wasn't available in our environment); they use only standard TestNG annotations and Assert methods, so they run unchanged with mvn test in a TestNG project.

The tests confirm how Scanner behaves: it doesn't care whether values are separated by spaces or new lines; "ten" instead of a number throws InputMismatchException; and too few values throws NoSuchElementException — so a real program should catch these and ask again rather than crash. Step through the reading loop and watch the array fill in the Java Code Visualizer.

From Real Projects

Java has been the language of every automation framework I've worked with — Selenium, TestNG, POM classes and Apache POI for Excel data. Interviews for automation roles regularly include basic programs like this one, often followed by a question on OOP concepts. Practice writing it by hand and explaining how you'd test it. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. Always handle invalid input — text where a number is expected, or fewer values than promised.

📚 Official documentation: Java 21 API: java.util.Scanner · Oracle Java Tutorials: Arrays

🧩 Java Array Programs — 4 of 43

← Previous: How to Find the Length of an Array in Java

Next: Find Average of Array Elements in Java →

See every program in the Java coding programs index.

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.