Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
510 views
in Blog Post by 15 41 68

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

declare array in java


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:-

access array in java


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.

looping 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().

sorting asc and desc of array in java


Conclusion

In this post, we learned how to use arrays in Java.

See Also


If you don’t ask, the answer is always NO!
...