Arrays in Java
An overview of arrays and 2D arrays in Java.
StartKey Concepts
Review core concepts you need to learn to master this subject
Arrays
Arrays
String[] animals = {"Giraffe", "Elephant", "Toucan"};
// Access an element via its index:
System.out.println(animals[0]); // Prints: Giraffe
// Change an element value:
animals[1] = "Lion";
// Find number of elements in an array:
System.out.println(animals.length); // Prints: 3
// Traverse array using for loop:
for (int i = 0; i < animals.length; i++) {
System.out.println(animals[i]);
}
/* Prints:
Giraffe
Lion
Toucan
*/
// Traverse array using for-each loop
for (int i: animals) {
System.out.println(i);
}
/* Prints:
Giraffe
Lion
Toucan
*/
An array is a collection of values with the same data type.