Multidimensional Arrays
We can even create multidimensional arrays, i.e., arrays within arrays. We access values by providing an index for the array and another one for the value inside it.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[][] objects = {{"Spoon", "Fork", "Bowl"}, {"Salt", "Pepper"}};
//accessing array elements using indexing
System.out.println(objects[0][2]);
System.out.println(objects[1][1]);
}
}
Output:
Bowl
Pepper
We can also print the multi-dimensional array.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
int[][] objects = {{1,2,3}, {4,5,6}};
for (int i = 0; i < objects.length; i++) {
for (int j = 0; j < objects[i].length; j++) {
System.out.print(objects[i][j] + "\t");
}
System.out.println();
}
}
}
Output:
1 2 3
4 5 6
Use loops with arrays:
The simplest way of looping through an array is to use a simple for-each loop.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[] objects = {"Spoon", "Fork", "Bowl", "Salt", "Pepper"};
for (String i : objects) {
System.out.println(i);
}
}
}
Output:
Spoon
Fork
Bowl
Salt
Pepper
Alternatively, you can also use a simple for loop to do the same.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[] objects = {"Spoon", "Fork", "Bowl", "Salt", "Pepper"};
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
}
}
Output:
Spoon
Fork
Bowl
Salt
Pepper