Array input in java

In this article, we are going to see how we can take array input in java using a scanner.

What is an Array?

Array is the collection of similar data type value. Length of an array is fixed we can’t change length of an array after declaration. Memory allocation in array is contiguous.

Array Declaration in Java

We can declare an 1D array in java in following way

syntax :

data type[] array name = new data type[length of array]

or

data type array name[] = new data type[length of array]

Java Array declaration example

int[] array = new int[5];

or

int array[] = new int[5];

Here we given length of array is 5. all the 5 element can be accessed at a[0], a[1], a[2], a[3], a[4] because indexing in array start from 0 and goes to length -1;

How to take Array input in java

  • first we need to take input for the length of array n.
  • now we have to declare the array in desired data type
  • now we have to run a loop from 0 to length -1, take input using a scanner, and assign it to the array[0], array[1], array[2],……., a[n-1], where n is the length of the array
  • In the same way we can also print the array using loop by accessing one array element by index value

Java code for array input

package gangforcode;

import java.util.Scanner;

public class arrayInput {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // take input for length of array
        int n = sc.nextInt();
        // declare array of length n
        int[] array = new int[n];

        // use a loop for taking input from 0 index to n-1 index
        for(int i =0;i<n;i++)
            array[i] = sc.nextInt();


        // printing the elements of array

        for(int i=0;i<n;i++)
            System.out.print(array[i]+" ");
    }

}

Output

array input in java

You can also refer to the following you tube video for this tutorial of array input in java and printing array in java

array input in java

The same logic is applicable in all programming languages to take array input from the user

Thanks!!

Leave a Comment