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
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int arr_size = 0;
if (sc.hasNextInt()) {
arr_size = sc.nextInt();
}
int[] arr = new int[arr_size];
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++) {
System.out.print(arr[i] + " ");
}
sc.close();
}
}
|
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.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
23 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...