Java Reference
In-Depth Information
// Add a new line after each row is printed
System.out.println();
}
}
}
0 1
1
2 3 4
Initializing Multi-Dimensional Arrays
You may initialize the elements of a multi-dimensional array by supplying the list of values at the time of its
declaration or at the time of creation. You cannot specify the length of any dimension if you initialize the array with
a list of values. The number of initial values for each dimension will determine the length of each dimension in the
array. Since many dimensions are involved in a multi-dimensional array, the list of values for a level is enclosed in
braces. For a two-dimensional array, the list of values for each row is enclosed in a pair of braces, like so:
int[][] arr = {{10, 20, 30}, {11, 22}, {222, 333, 444, 555}};
This statement creates a two-dimensional array with three rows. The first row contains three columns with values
10, 20, and 30. The second row contains two columns with values 11 and 22. The third row contains four columns with
values 222, 333, 444, and 555. A zero-row and zero-column two-dimensional array can be created as shown:
int[][] empty2D = { };
Initialization of a multi-dimensional array of reference type follows the same rule. You can initialize a
two-dimensional String array like so:
String[][] acronymList = {{"JMF", "Java Media Framework"},
{"JSP", "Java Server Pages"},
{"JMS", "Java Message Service"}};
You can initialize the elements of a multi-dimensional array at the time you create it.
int[][] arr = new int[][]{{1, 2}, {3,4,5}};
Enhanced for Loop for Arrays
Java 5 introduced an enhanced for loop that lets you loop through elements of an array in a cleaner way. The
enhanced for loop is also known as for - each loop. The syntax is as follows:
for(DataType e : array) {
// Loop body goes here...
// e contains one element of the array at a time
}
 
Search WWH ::




Custom Search