Introduction:
Welcome to the Java tutorial on Multi-Dimensional Arrays. I would highly recommend you have a look at my Arrays page before reading through this one!
What is a Multi-Dimensional Array?
A Multi-Dimensional Array is an array which contains more than one index at any given placement. For example; instead of just having a value at the index "3", we could have "3""0", "3""1" etc.
When are Multi-Dimensional Arrays Used?
Compared to arrays there are not used as often. A good purpose for Multi-Dimensional Arrays is when you have sub-topics or values of main topics or values. So for example we could have some titles or books and games, like shown below (theory):
(0 = Books, 1 = Games)
[0][0] = "Book A"
[0][1] = "Book B"
[0][2] = "Book C"
[1][0] = "Game A"
[1][1] = "Game B"
[1][2] = "Game C"
Examples:
Here are some code samples to help you understand:
myArray[0][0] = "Book A";
myArray[0][1] = "Book B";
myArray[0][2] = "Book C";
myArray[1][0] = "Game A";
myArray[1][1] = "Game B";
myArray[1][2] = "Game C";
System.
out.
println(myArray
[0][2]); System.
out.
println(myArray
[1][1]); String[][] presetArray
= {{"Book A",
"Book B",
"Book C"},
{"Game A",
"Game B",
"Game C"}}; System.
out.
println(presetArray
[1][2]);
The above code outputs the following...
Finished!