In this post, we're gonna learn about arrays in Java.
What is an Array?
Array is a data structure that used to store multiple values in one single variable instead of declaring separate variables for each value.
Arrays in Java
- An array in java is a container that holds values of the same data type.
- Each element in the array has an index that starts from 0 index.
- It is declared like others variable with [] after the data type.
- Using the array length to find the number of elements the array contains.
- the size of the array specified with int.
Array declaration in Java
datatype[] arrayName;
Data Type: It defines the element type of the array.
[ ]: It defines the size of the array.
arrayName: It is the Name of array
Access an array element in Java
Each element in the array has an index that we can access the element by it.
For example when you want to return the first element in the array:-
Array length in Java
- Since arrays are objects in C#, we can find its length using the length property.
- The array contains specific numbers of element.
System.out.println(cars.length); // Outputs 4
Looping array elements in Java
by using the for loop or for each and the length property of the array we can looping the array elements in Java.
Sort arrays in Java
- Arrays.sort() is an array method that used to sort the array element alphabetically in ascending order.
- We can sort the array in descending order using Collections.reverseOrder().
Conclusion
In this post, we learned how to use arrays in Java.
See Also