This week up to 80% off on C# .NET courses. More info

# Lesson 10 - Multidimensional arrays in Java

In the previous exercise, Solved tasks for Java lesson 9, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on multidimensional arrays in Java instead of a thorough-full lesson? Here it is:

Shortened initialization of a 2D array:

```int[][] cinema = {
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }
};```

Writing `1` at the position ``:

`cinema = 1;`

Reading the value (now `1`) at the position ``:

``````{JAVA_CONSOLE}

int[][] cinema = {
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }
};
cinema = 1;

System.out.println(cinema);
{/JAVA_CONSOLE}``````

Printing the whole 2D array:

``````{JAVA_CONSOLE}

int[][] cinema = {
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }
};
cinema = 1;

for (int j = 0; j < cinema.length; j++) {
for (int i = 0; i < cinema.length; i++) {
System.out.print(cinema[j][i]);
}
System.out.println();
}
{/JAVA_CONSOLE}``````

Declaring an empty 2D array of a given size:

`int[][] cinema = new int;`

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Solved tasks for Java lesson 9, we learned how to use the `split()` and `join()` methods. Today's tutorial is basically a bonus when it comes to Java basic constructs. We'll discuss what we call multidimensional arrays. Essentially, you could skip directly to the object-oriented programming course; however, I highly recommend that you finish this course first, so you could understand the remaining techniques. After all, this is still just the basics.

We've already worked with a one-dimensional array which we can imagine as a row of boxes in computer memory. (An array of eight numbers can be seen in the image)

Although it's not too common, you may sometimes encounter multidimensional arrays. Especially, when it comes to game applications.

## Two-dimensional array

A good representation of a 2-dimensional array is a grid because technically, it is one. A practical application for 2-dimensional arrays would be to use them to store the available seats in a cinema. Here's a visual representation of what I'm referring to: (We can see the available seats of a cinema in the picture )

Of course, the cinema would be bigger in real life, but this array is just fine as an example. `0` means the seat is available, `1` stands for one that isn't. Later, we could also add `2` for reserved seats and so on. It would be more appropriate to create our own data type (called enumerable) for these states, but we'll get into that later. For now, we'll work with numbers.

Java actually doesn't offer any special support for multidimensional arrays, however, we can easily declare them as an array of arrays. The cinema declaration could look like this:

`int[][] cinema = new int;`

The first number indicates the number of columns, the second is the number of rows, we could treat it the other way around as well, for example, matrices in mathematics have the number of rows come first.

All numeric arrays in Java are automatically initialized with zeros after the declaration, guaranteed. We've just created a table full of zeros.

### Filling the data

Let's fill the cinema room with 1s now as you can see in the picture above. Since we'll be lazy as good programmers should be, we'll use `for` loops to create a row of 1s To access an item of a 2D array we have to enter two coordinates.

```cinema = 1; // center
for (int i = 1; i < 4; i++) { // fourth row
cinema[i] = 1;
}
for (int i = 0; i < 5; i++) { // the last row
cinema[i] = 1;
}```

### The output

We'll print the array using a loop as we did before. We'll need 2 loops for the 2d array, the first one will iterate over columns and the second one over rows). As proper programmers, won't specify the number of rows and columns directly into the loop because it may change in the future.

We need to keep in mind that if we ask for `cinema.length`, it'll contain the number of columns (the length of the outer array representing columns). To determine the number of rows (the length of an inner array representing a column) we'll ask for `cinema.length`. Notice that there has to be at least 1 column to make it work.

We'll nest the loops in order so the outer loop would iterate over the rows and the inner one over the columns of the current row. After printing a row, we must break a line. Both loops must have a different control variable:

``````{JAVA_CONSOLE}

// declaration
int[][] cinema = new int ;
// filling with data
cinema = 1; // center
for (int i = 1; i < 4; i++) { // fourth row
cinema[i] = 1;
}
for (int i = 0; i < 5; i++) { // the last row
cinema[i] = 1;
}

for (int j = 0; j < cinema.length; j++) {
for (int i = 0; i < cinema.length; i++) {
System.out.print(cinema[i][j]);
}
System.out.println();
}
{/JAVA_CONSOLE}``````

The result:

```Console application
00000
00000
00100
01110
11111```

## N-dimensional arrays

Sometimes, it may be useful to create an array of even more dimensions. We can all at least imagine a 3D array. Adding on the cinema analogy, we'll say ours has multiple floors, or generally more rooms. The visualization could then look like this: We can create a 3D array the same way we created the 2D array:

`int[][][] cinemas = new int;`

The code above creates the 3D array you saw in the picture. We can access it through the indexers, square brackets, as before, but now we have to enter 3 coordinates.

`cinemas = 1; // the second-floor cinema, the third row, the fourth seat`

If we ask for `cinemas.length`, we'll get the number of "floors".

## Jagged arrays

We doesn't have to specify the same length for all the columns. This results into "jagged arrays". An advantage to declaring 2D arrays this way is that we can store as large of an array as we want in each row/column. We can spare some memory this way. The declaration would look something like this:

`int[][] cinema = new int[];`

And we can imagine the array as this: The disadvantage of this approach is that we need to initialize the array ourselves. The first row of five cells exists, but we'd have to insert the individual columns into it ourselves (we'll insert all the columns with 5 items for now):

```for (int i = 0; i < cinema.length; i++) {
cinema[i] = new int;
}```

Java also doesn't make it any easier to retrieve the number of rows and columns of these arrays. We have to determine the array size like this:

```int cols = cinema.length;
int rows = 0;
if (cols != 0) {
rows = cinema.length;
}```

Notice how it's necessary to retrieve the number of columns first. If it is `0`, we can't access the first column to determine its length (number of rows in the column).

The values of the array can be accessed using 2 indexers:

`cinema = 1; // we occupy a seat at the 5th column and the 3rd row`

## Shortened initialization of multidimensional arrays

I'll also mention that even multidimensional arrays can be initialized with values directly (the code creates and initializes a crowded cinema room as you can see in the picture):

```int[][] cinema = {
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 1, 1, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 1 }
};```

(The array in this code is rotated since we define columns which are declared as rows here).

We can use a similar initialization even for jagged arrays (the code below creates the jagged array from the picture):

```int[][] jaggedArray = {
new int[] {15, 2, 8, 5, 3},
new int[] {3, 3, 7},
new int[] {9, 1, 16, 13},
new int[] {},
new int[] {5}
};```

In conclusion, I would like to add that some people who can't use objects properly, use 2D arrays to store multiple sets of data of a single entity. e.g. imagine that we want to store the length, width, and height of five cell phones. Although you may think that a 3D array would be best for the situation, it can be pulled off with an ordinary 1D array (specifically a list of objects of the `Phone` type). We'll go over all of that in the object-oriented programming course. If you feel like you could still use some more practice, go ahead and give the exercises for this lesson a shot.

In the next lesson, Mathematical functions in Java - The Math library, we'll look at basic math functions and finish the basic constructs course.

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily. David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.