Array in java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays.
- In Java, all arrays are dynamically allocated.
- Arrays are stored in contiguous memory [consecutive memory locations].
- Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.
- A Java array variable can also be declared like other variables with [] after the data type.
- The variables in the array are ordered, and each has an index beginning with 0.
Read more here Arrays in Java
How to take array input from the user in Java?
In Java, you may utilize loops and the Scanner class to accept an array input from the user. Here’s an example of how to accomplish it:
Java
// Java program that accepts // array input from the user. import java.util.Scanner; public class GFG { 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 arr_size = 0 ; if (sc.hasNextInt()) { arr_size = sc.nextInt(); } // Initialize the array's // size using user input int [] arr = new int [arr_size]; // Take user elements for the array System.out.println( "Enter the elements of the array: " ); for ( int i = 0 ; i < arr_size; i++) { if (sc.hasNextInt()) { arr[i] = sc.nextInt(); } } System.out.println( "The elements of the array are: " ); for ( int i = 0 ; i < arr_size; i++) { // prints the elements of an array System.out.print(arr[i] + " " ); } sc.close(); } } // Code Contributed By Sufian Ansari |
Input:
Enter the size of the array: 5
Enter the elements of the array: 10 20 30 40 50
Output:
The elements of the array are: 10 20 30 40 50
Explanation:
In this example, we first utilize 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’arr_size’. 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.