Two-Dimensional Arrays in Java

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

This is one of the articles from our Java Tutorial for Beginners.

Do you already know what arrays in Java are and how to work with them?

  1. If the answer is "No," then start by reading this article: "Java Arrays"
  2. If the answer is "Yes," then read the article below, which is about two-dimensional arrays in Java.

Since you already know what arrays are and how to work with them, it should be easy for you to:

  • create a one-dimensional array
  • assign values to it
  • and display it in the console

Example:

How Do We Create Two-Dimensional Arrays?

The most popular example of a two-dimensional array is probably the matrix. If you've forgotten what a matrix is, here's a reminder:

array_vertex-academy-2

A matrix has rows and columns. Specific values stand at the intersections of these rows and columns.

Note: The index numbers of elements in arrays start from 0.

Number 1 is at the intersection of row 0 and column 0.

Number 2 is at the intersection of row 0 and column 1.

Number 3 is at the intersection of row 1 and column 0.

Number 4 is at the intersection of row 1 and column 1.

There are two ways to create two-dimensiona arrays:

1. In the code below, we created a two-dimensional array, but we didn't assign it any values.

2. With this approach, we created a two-dimensional array and assigned it values at the same time.

When you create an ordinary array, you use one pair of brackets. In a two-dimensional array, you use two pairs of brackets.

  • In the first pair of brackets, you write the quantity of rows.
  • In the second pair of brackets, you write the quantity of columns.

Example:

And How Do We Display a Two-Dimesional Array In the Console?

The output of a two-dimensional array (with the help of the "for" loop) is very different from the output of an ordinary array with a "for" loop.

In order to display a value in each cell of a two-dimensional array, it's not enough to use a single "for" loop; instead, it's necessary to use two "for" loops, and one of them has to be located inside the other.

Why?

We mentioned earlier that a two-dimensional array consists of rows and columns, and each cell of such an array is at the intersection of a row and a column.

The first "for" loop checks each element of each row of a two-dimensional array (that contains come quantity of columns) to see if it matches the conditions.

The second "for" loop checks each element of each column in each row. By inserting one "for" loop inside another, you can assign values to elements of a two-dimensional array.

Example:

If you run this code on your computer, you will see the following in the console:

1    2
3    4

 


You can find more articles in our Java Tutorial for Beginners.

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr
Самоучители--узнать детальнее--