Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Two-Dimentional Array | Arrays
Java Basics
course content

Course Content

Java Basics

Java Basics

1. Getting Started
2. Basic Types, Operations
3. Loops
4. Arrays
5. String

bookTwo-Dimentional Array

Matrix? Dimension? What??

A two-dimensional array is equivalent to a matrix in mathematics. (If you're unfamiliar with matrices, don't worry; I'll explain them simply right now.) While two-dimensional arrays aren't commonly used in practical programming, it's important to understand them and the ability to create multi-dimensional arrays. A two-dimensional array is an array with two distinct indices.

To illustrate, let's examine a diagram of a two-dimensional array:

The table above serves as an example of a two-dimensional array or matrix. Let's explore how to retrieve values from this table. For instance, suppose we want to find the element at index [3][2]. The first index indicates the row we will examine, and the second indicates the column. Visualizing two lines mentally can help us arrive at the result:

We draw two lines intersecting at the cell with the number 18. This represents the value at index [3][2].

I hope you now have a clear understanding of how matrices work. Next, let's explore how to declare a two-dimensional array in code, and then we'll demonstrate how to populate it manually. Following that, we will conduct an index-based search to confirm our accuracy.

java

Main

copy
1234567891011121314151617
package com.example; public class Main { public static void main(String[] args) { int[][] twoDimensionalArray = new int[3][3]; twoDimensionalArray[0][0] = 1; twoDimensionalArray[0][1] = 2; twoDimensionalArray[0][2] = 3; twoDimensionalArray[1][0] = 4; twoDimensionalArray[1][1] = 5; twoDimensionalArray[1][2] = 6; twoDimensionalArray[2][0] = 7; twoDimensionalArray[2][1] = 8; twoDimensionalArray[2][2] = 9; System.out.println(twoDimensionalArray[2][1]); } }

As you can see, we declared a two-dimensional array with dimensions 3 x 3. However, manually filling it proved to be quite time-consuming and challenging. You might already be contemplating how we can utilize a loop to efficiently populate the array or extract all the data from it. We will delve into that topic in the next chapter.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 4
some-alt