+ 2
Please explain this program
public class Program { public static void main(String[] args) { int[ ][ ] myArr = { {1, 2, 3}, {4}, {5, 6, 7} }; myArr[0][2] = 42; int x = myArr[1][0]; System.out.println(x); } }
8 Answers
+ 2
myArr is a multidimensional array. (There are three arrays inside an array)
0 --> first array
0,0 = 1
0,1 = 2
0,2 = 3
1 --> second array
1,0 = 4
2 --> third array
2,0 = 5
2,1 = 6
2,2 = 7
myArr[0][2] = 42 //change the
value at [0][2]
// myArr now:{ {1,2,42},{4},{5,6,7} }
int x = myArr[1][0]; //x gets the value from [1][0] --> 4
System.out.println(x);
//output 4
+ 2
Priyanka G myArr[0][2] = 42 could be an example to show you that you can change a value inside an array.
+ 2
Priyanka G It is an example:
" You can get and set a multidimensional array's elements using the same pair of square brackets." (The text above the code explains it)
https://www.sololearn.com/learn/Java/2149/?ref=app
+ 1
But why myArr[1 ] [ 2]=42; they are use in program
+ 1
Rictus thx. A typo. I changed it.
0
You output a number from an array made of arrays : x is 4
0
the âmyArr[0][2] = 42â line means that from the first (Java arrays start counting from cero) array, we take the third value, 3, and change its value to 42, at this point of the code it really doesnât change much to the output as we are printing 4(Which is [1][0]), not 42(Which is [0][2]). Hope that helped.
0
Denise, I think in the first array 3 is 0,2 not 0,3