How to Take Array Input From User in Java?
Last Updated :
17 Apr, 2025
Arrays in Java are an important data structure, and we can add elements to them by taking input from the user. There is no direct method to take input from the user, but we can use the Scanner Class or the BufferedReader class, or the InputStreamReader Class.
1. Using Scanner Class to Take Array Input
Approach:
- First, we create an object of the Scanner Class and import the java.util.Scanner package.
- Then create a variable for taking the size of the array from the user, and show the message "Enter size of array"
- Then we use the hasNextInt() and nextInt() methods of the Scanner class to take integer input from the user through the console.
- Then we print each element of the array using a loop.
- Then we close the Scanner object when we have completed the program for best practice.
Example: Taking input from the user in a one-dimensional array using the Scanner class and loops.
Java
// Java program to take 1D array
// input from the user
// using Scanner class and loops
import java.util.Scanner;
public class Geeks
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Take the array size from the user
System.out.println("Enter the size of the array: ");
int s = 0;
if (sc.hasNextInt()) {
s = sc.nextInt();
}
// Initialize the array's
// size using user input
int[] arr = new int[s];
// Take user elements for the array
System.out.println(
"Enter the elements of the array: ");
for (int i = 0; i < s; i++) {
if (sc.hasNextInt()) {
arr[i] = sc.nextInt();
}
}
System.out.println(
"The elements of the array are: ");
for (int i = 0; i < s; i++) {
System.out.print(arr[i] + " ");
}
sc.close();
}
}
Output:
Explanation: In this example, first we use the Scanner class to accept user input and save the array size in the size variable. Then we make an array arr with the size s. Following that, we use a for loop to accept user input and save it in an array. Finally, we use another for loop to print the array's elements.
The Scanner class from java.util helps to take user input. We can use the Scanner class with loops to take input for individual array elements (to use this technique, we must know the length of the array).
In this example, we will understand how to take input for a two-dimensional array using the Scanner
class and loops.
Approach:
- First, we create an object of the Scanner Class and import the java.util.Scanner package.
- Then create two variables for taking the row and column size of the array from the user, show the message to enter the row and column one by one.
- Then we use the hasNextInt() and nextInt() methods of the Scanner class to take integer input from the user through the console with nested loop.
- Then we print each element of the array using nested for loop.
- Then close the Scanner object.
Example: Taking input of Two dimenstional array from the user.
Java
// Java program to take 2D array input from the user
// Using Scanner class and loops
import java.util.Scanner;
public class Geeks {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Prompt the user for the dimensions of the array
System.out.print("Enter the number of rows: ");
int r = sc.nextInt();
System.out.print("Enter the number of columns: ");
int c = sc.nextInt();
// Create the 2D array
int[][] arr = new int[r][c];
// Prompt the user to enter values for the array
System.out.println("Enter the elements of the array:");
// Input loop to populate the array
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
System.out.print("Enter element at position [" + i + "][" + j + "]: ");
arr[i][j] = sc.nextInt();
}
}
System.out.println("The entered 2D array is:");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
System.out.print(arr[i][j] + " ");
}
// Move to the next line for the next row
System.out.println();
}
// Close the Scanner object
sc.close();
}
}
Output:
Explanation: In this example, first we use the Scanner class to accept user input of the number of rows and columns to create a 2D array. Then, we use a for loop to accept user input and save it in the 2D array. Finally, we use another for loop to print the array's elements.
We can use the BufferedReader and InputStreamReader classes to read user input in Java and use the IOException class to handle exceptions in input.
In the below example, we use the BufferedReader object to read user input and manage the input classes that even with the wrong input type the error is not thrown.
Approach:
- Initialize the important packages in the program mentioned in the below code such as BufferedRead, IOException and InputStremReader from java.io.
- In the method where we use the BufferedReader and InputStreadReader throws the IOException
- Then initialize the object of InputStreamReader and pass the System.in in the constructor.
- Then create the object of BufferedReader and pass the InputStreamReader object in the constructor.
- Take the size of the array from the user. The BufferedReader read the String and we use the ParseInt() method so if the user enter other than the integer number then it will throw exception so handle it using try catch.
- Then take the input of the array elements from the user and print it using the loop
- In the end close the BufferedReader object.
Example: Taking input of an array from user using BufferedReader and InputStreamReader.
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Geeks
{
public static void main(String[] args) throws IOException
{
// Initializing the object InputStreamReade
InputStreamReader in = new InputStreamReader(System.in);
// Initializing the object of BufferedReader
BufferedReader br = new BufferedReader(in);
// Take the array size from the user
System.out.println("Enter the size of the array: ");
int s = 0;
try {
s = Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
System.out.println("Invalid input for array size. Please enter a valid integer.");
return;
}
// Initialize the array's
// size using user input
int[] arr = new int[s];
// Take user elements for the array
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < s; i++) {
try {
arr[i] = Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
System.out.println("Invalid input for array element. Please enter a valid integer.");
return;
}
}
System.out.println("The elements of the array are: ");
for (int i = 0; i < s; i++) {
System.out.print(arr[i] + " ");
}
// Close the BufferedReader
br.close();
}
}
Output:
Explanation: In this example, we use BufferedReader and InputStreamReader classes to capture user input and construct an array based on the specified size. We make an array arr with the size s. We handle potential input errors with try-catch blocks. Then, we initialize and populate an array with user input, and use a loop to print its elements.
Similar Reads
How to Take Input From User Separated By Space in Java ? There are 2 methods to take input from the user which are separated by space which are as follows: Using BufferedReader Class and then splitting and parsing each valueUsing nextInt( ) method of Scanner class Let us discuss both the methods one by one in order to get a better understanding by impleme
3 min read
How to Fill (initialize at once) an Array in Java? An array is a group of like-typed variables that are referred to by a common name. In this, article we will learn about Filling array in Java while Initialization.Example:Java// Java program to fill the element in an array import java.util.*; public class Geeks { public static void main(String args[
3 min read
How to Convert JSON Array to String Array in Java? JSON stands for JavaScript Object Notation. It is one of the widely used formats to exchange data by web applications. JSON arrays are almost the same as arrays in JavaScript. They can be understood as a collection of data (strings, numbers, booleans) in an indexed manner. Given a JSON array, we wil
3 min read
How to Declare an ArrayList with Values in Java? ArrayList is simply known as a resizable array. Declaring an ArrayList with values is a basic task that involves the initialization of a list with specific elements. It is said to be dynamic as the size of it can be changed. Proceeding with the declaration of ArrayList, we have to be aware of the co
2 min read
Program to convert Boxed Array to Stream in Java An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case
3 min read
How to Print an Array in Java Without using Loop? Given an array arr in Java, the task is to print the contents of this array without using any loop. First let's see the loop method. Loop method: The first thing that comes to mind is to write a for loop from i = 0 to n, and print each element by arr[i].Pseudo Code: for(int i = 0; i < Array.lengt
2 min read
How Objects Can an ArrayList Hold in Java? ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java just as Vector in C++. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. In order to understan
3 min read
Convert a String to Character Array in Java Converting a string to a character array is a common operation in Java. We convert string to char array in Java mostly for string manipulation, iteration, or other processing of characters. In this article, we will learn various ways to convert a string into a character array in Java with examples.E
2 min read
Java Program to Check Array Bounds while Inputting Elements into the Array Concept: Arrays are static data structures and do not grow automatically with an increasing number of elements. With arrays, it is important to specify the array size at the time of the declaration. In Java, when we try to access an array index beyond the range of the array it throws an ArrayIndexOu
4 min read
Java Program to Convert an Array into a List In Java, arrays and lists are two commonly used data structures. While arrays have a fixed size and are simple to use, lists are dynamic and provide more flexibility. There are times when you may need to convert an array into a list, for instance, when you want to perform operations like adding or r
4 min read