Java 8 | Two Dimensional Array
Hi y’all! Welcome to another Java session with me, and today I’m going to talk about the Two Dimensional Array. This is not that different with the one dimensional array, only difference between them, is that the two dimensional array is just a array of the one dimensional array! So before we go, it’d be better if you check out my post about one dimensional array.
Java 8 | One Dimensional Array
One dimensional array — a collection of elements, that has same data type, in a horizontal style.
[Two Dimensional Array]
So to declare the two dimensional array is not that difficult. You can just put one more set of brackets in the one dimensional array declaration, like below.
Then the first brackets means the number of the rows of the array, and the second one means the columns. So in the picture, you can see I declared the two dimensional array that has 2 rows and 3 columns! And as always the indexes are starting with the 0.
And you would remember that we could initialize one dimensional array with the braces. It also works with two dimensional array.
Just like this! And to see the whole values of the array I used nested for loop. And you might also noticed that I put the condition of the second for loop as
col < two.length; .
In the two dimensional array,
arr.length; means the number of its rows, and
arr.length; means how many columns are in the row . We can use that since in one array there are same numbers of the columns on each row. In my case If I put
two.length; it would be working the same as well!
To get to know the two dimensional array better, I brought you a basic practice question. Let’s do this on your own!
[Question] Use the code below, put the numbers like the sample and print it out on the console.
** Code **
int two = new int;* Sample **
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
The answer is right on below.
I declared the int variable
val which has 1 as initial value. And as you see, every time the for loops repeated val gets bigger one by one because of the increment operator
val++. If you’re unfamiliar with the increment/decrement operator yet, checkout my last post!
Java 8 | Increment / Decrement Operator
Hi guys! I know last time I told you that I’m going to talk about the two dimensional array this time, but I thought…
Well that is all for today guys! I hope you all enjoyed this, thank you for reading my post! See ya!