Example 1: Multidimensional array in java
public class TwoDimensionalStringArray
{
public static void main(String[] args)
{
String[][] animals = {
{ "Lion", "Tiger", "Cheetah" },
{ "Deer", "Jackal", "Bear" },
{ "Hyena", "Fox", "Elephant" } };
for(int a = 0; a < animals.length; a++)
{
System.out.print(animals[a][0] + " ");
for(int b = 1; b < animals[a].length; b++)
{
System.out.print(animals[a][b] + " ");
}
System.out.println();
}
}
}
Example 2: how to declare an array in java
An array is an ordered collection of elements of the same type, identified by a pair of square brackets [].
To use an array, you need to:
1. Declare the array with a name and a type. Use a plural name for array, e.g., marks, rows, numbers. All elements of the array belong to the same type.
2. Allocate the array using new operator, or through initialization, e.g.
int[] marks;
int marks[];
marks = new int[5];
int[] factors = new int[20];
int[] numbers = {11, 22, 33, 44, 55, 66};
Example 3: Arrays in java
public class AccessingArrayElements
{
public static void main(String[] args)
{
int[] arrNum = {25, 23, 15, 20, 24};
for(int a = 0; a < arrNum.length; a++)
{
System.out.println(arrNum[a]);
}
}
}
Example 4: Multidimensional array in java
import java.util.ArrayList;
import java.util.List;
public class Dynamic2dArray
{
public static void main(String[] args)
{
List<int[]> li = new ArrayList<>();
li.add(new int[]{2,4,6});
li.add(new int[]{3,5});
li.add(new int[]{1});
System.out.println("Element at [0][0]: " + li.get(0)[1]);
System.out.println("Element at [1][1]: " + li.get(1)[1]);
}
}
Example 5: Java create array of array
String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };