0

Can someone explain me this code one by one line... please

public class Main { public static void main(String[] args) { int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; for (int i = 0; i < myNumbers.length; ++i) { for(int j = 0; j < myNumbers[i].length; ++j) { System.out.println(myNumbers[i][j]); } } } }

13th Oct 2021, 6:41 PM
Disha Jain
2 Answers
+ 1
Hello! Your program is printing a 2D array. Essentially when we create 2D arrays in Java, we are creating the rows we want below every time we add more brackets. Its easier to think about if instead you write your array as: int[][] myNumbers = { {1,2,3,4}, {5,6,7} } This way you can see how you are adding rows to the array. When you use myNumbers.length, this refers to the number of rows you have. In your code, you use: for(int i = 0; i < myNumber.length; i++) You have two rows so you are iterating over those two which are: 1,2,3,4 5,6,7 Inside this loop, you call another a loop which iterates over that row at the specified index. for(int j = 0; j < myNumbers[i].length; ++j) myNumbers[i] points to which row you are currently on. Finally you are printing out the number at that index using the i and j as its position.
13th Oct 2021, 7:04 PM
Jibraeel Abdelwahhab
Jibraeel Abdelwahhab - avatar
+ 1
https://code.sololearn.com/cFMxuli27p72/?ref=app Heres a version in code that shows the explanation more clearly
13th Oct 2021, 7:05 PM
Jibraeel Abdelwahhab
Jibraeel Abdelwahhab - avatar