- Home
- Training Library
- Programming
- Programming Courses
- Methods in Java

# 2D Arrays

## Contents

###### Methods

## The course is part of this learning path

This course looks at methods, which are named, self-contained blocks of code that you can call upon to help solve problems for you. We'll then take a look at some projects which will put methods into practice.

### Learning Objectives

- Understand the fundamentals of writing your own methods
- Learn how to classify methods by their return types as well as their parameters
- Learn about parameter passing schemes that are used by programming languages to determine how methods treat their parameters
- Explore method overloading and two-dimensional arrays

### Intended Audience

- Beginner coders or anyone new to Java
- Experienced Java programmers who want to maintain their Java knowledge
- Developers looking to upskill for a project or career change
- College students and anyone else studying Java

### Prerequisites

This is a beginner-level course and can be taken by anyone with an interest in learning about Java.

In this section, we have covered a lot about methods. Although I could have included this lecture's topic which is 2D Arrays in the earlier section on arrays and array lists. I chose to save it, for now, so you could use it together with methods. This topic will help you out a tremendous amount in our Tic-Tac-Toe project later on in the section. The regular built-in arrays we saw in an earlier section in this course are also called one-dimensional arrays, because they contain data in a linear way, like a single row of data. But you can also have multi-dimensional arrays by adding additional sets of square brackets. One of the most popular forms of these multi-dimensional arrays is the two-dimensional array, which has two sets of square brackets. We often visualize and describe 2D arrays by saying that the first dimension represents the rows, and the second dimension represents the columns.

So, if you're familiar with linear algebra, you may recognize that 2D arrays are much like matrices. We could also say that multi-dimensional arrays, which can be 3D, 4D or many more dimensions, are a generalization of matrices. In mathematics, the term that we often use to describe the generalization of the matrix is tensor. If you've done any work with Python, especially with data science, you might be familiar with TensorFlow, which does provide for tensor functionality in an efficient manner.

So, let's see what the actual code looks like now so that we at least have an idea of the practical application of the theory and concepts behind 2D arrays. So, let's create a file called FunWith2DArrays. So, right here 'right' click 'New Java Class'. FunWith2DArrays. So, we have this and we're going to create public static void main with the parameter, a string array. And of course, we're going to have a couple other methods that we're going to use. One of them will be called fill2DArray. So, let's make that. public static void fill2DArray, and it's 2D so I have two sets of square brackets. And we'll just call it twoDArr. That's the end of the fill2DArray. And then we also want another one here, public static void print2DArray (int[ ][ ] twoDArray) and end of print2DArray. So, for printing, if we visualize this, we could write either of these first, to be honest. But to visualize this for printing, it's actually pretty simple.

I'm going to use, I guess an enhanced for loop, a range-based for loop. So, every element, we can think of every element in a 2D array. If you look at just the first index is really an array in and of itself, a single dimensional array. So, you can think of it as each dimension or each element in the outermost array is pointing to another full array. But we tend to visualize it as rows and columns, like a Excel spreadsheet or something like that. But in actual memory, it's just one array whose elements are references to other arrays. So, I'm going to say that each element in twoDArr, if I don't use brackets here, if I just say each of these elements in the twoDArr, they are not integers but they'are integer array of single dimensions. So, that's pretty cool. So, what do I do? So, now I can say, each number in each of these single dimensional arrays, I can say System.out.print actually just print not println, and I'm going to put a little space there, and this is the end of inner for loop. And then right here, I'm going to print out a new line. All right, for the filling of the array, I'm going to randomize. I'm going to actually need to import this.

So, create a new random number generator. And I can do 'Alt + Enter' and import the class, and you can see that it's java.util.Random. So, I'm creating this random number generator and this time I'll use a regular for loop. i = 0, i < twoDArr.length, that's the outermost dimension or the number of rows, end for i. And then the innermost dimension, we have twoDArr[i], Since they're all the same, I could actually just say at zero, but in this case it doesn't really matter. So, I'm going to randomize 0 through 99 (inclusive). So, let's do this. twoDArr[i][j] so at row i, column j, I set it rand.nextInt and pass a 100. So, that goes from 0 through 99 (inclusive). So, row i, column j. Very good.

Now we have to, of course test it inside main. So, inside main we have a 2 row x 3 column matrix. The rows are horizontal, that's left to right, and the columns are vertical, that's up and down. And again you can think of a 2D array as a bit like a part of an Excel worksheet, except instead of using letters and numbers, we're using all numbers. So, when I say this, int[][] my2DArray = new int S2 rows x 3 columns. Very good. I'm now going to call fill2DArray and pass (my2DArray); so that will actually populate the array with random numbers 0 through 99 and that's what we wrote down here, correct. And now, I'm going to print it.

So, print2DArray. And I'm going to pass it that same 2DArray that we just filled. And since it's passed by value in Java, but it's passing a reference because the value of a reference type is a memory address. It's going to actually affect the array in memory. So, let's see what we have here when we run this. So, 'right' click 'FunWith2DdArrays' 'Run' , and there you go. So, you've got these numbers right here and you can see there's one row, two rows, right? And then 1-2-3 columns. And you'll notice if I run it again since it's randomized, you're going to get different numbers, right? So, you're getting all one to two digit numbers, and we are getting different numbers as we rerun it. Great.

So again, visually we can see the contents of our 2D array in tabular format. Another piece of information that is important to understand now that we've seen a visual is that a 2D array again is like a single dimensional array, whose elements are references to other single dimensional arrays. So, in our 2 x 3 array case, the row dimension has valid indices 0 and 1, correct? The element at index 0 is a reference to a whole other integer array, single-dimensional integer array, whose size is 3 because there are three columns. The element at index 1 is another reference to a completely different integer array. If you had a 3D array, each of its first dimension indices would hold references to a 2D array, you could think of it as. And then those in turn would have elements that are references to one-dimensional arrays. It can get pretty crazy from there and it's difficult to visualize much higher than three dimensions.

It is interesting to note that technically, Java's specification allows up to 250 five-dimensions for an array, but I don't personally find myself using such high dimensions. However, in different applications, like some areas of physics and data science, you will often use fairly high dimension arrays again, sometimes called tensors. Before moving on, I have a short challenge for you. Using the same FunWith2DArrays file, write and test another method called twice2DArray, which will take a two-dimensional integer array as a parameter and will double the values of each element in the 2D array. Make sure to test this method by placing a call to it after the methods we've already called in main. You will also want to call the print2DArray method to verify that your doubling of the values worked. So, pause the video, and give this one your best shot. Come back when you're done or if you need some help.

How'd that go for you? Were you able to complete this challenge? Let's work on it together. All right. So, we're going to create our new method here, public static void twice2DArray and it takes a 2D integer array. Here we go. And we're going to go through it with i and j. This time I chose to use a regular old for loop. int j = 0; j < twoDArr and we are going to say at [i].length. But again, you could just use that zero because these are the same. And we're doing j++. Okay, so now, 2DArr, and we can treat this just like a plain old integer because that's essentially what it is. So, I'm going to use the shortcut syntax, *=2. So, that's the same as saying, twoDArr[i][j] = twoDArr[i][j] * 2. It's a shortcut.

That's our compound multiplication, assignment operator. And of course, we want to call it in main, otherwise, we won't get any kind of solution. So, we're going to call twice2DArray and pass it (my2DArray); so that will actually modify it. And then we want to print it again. And of course let's run it, so that we can verify that this works. 'Right' click, 'Run' and you will see that in fact, this is our initial values 61, 59, 81. And then, the other one down here is those values in the corresponding positions doubled. If you need a little bit more space here, System.out.println(); we can do that, and we can run it again. And of course it will give us different numbers. So, 8 * 2 is 16, 58 * 2 is 116, 10 * 2 is 20, etc. So, it does appear that everything's working great. In the next lecture, we'll work on our first project for the section- a sum of elements project, where you'll work with methods and ArrayLists. I'll see you there.

John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.