+ 2

To understand better(explain)

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][1]; System.out.println(x); } } Output: exception error 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[2][1]; System.out.println(x); } } Output:6

9th Jul 2020, 4:46 AM
Aman Pushp
Aman Pushp - avatar
4 odpowiedzi
+ 3
The second row of array <myArr> only has one column { 4 }. The first code tried to refer myArr[1][1] (second column of the second row) which does not exist. The second code refers to the second column of the third row, there's no problem, as the third row has three columns { 5, 6, 7 }
9th Jul 2020, 4:56 AM
Ipang
+ 2
Kiibo Ghayal, I think he want someone to explain the code like what Ipang did. Thanks for your question and happy coding.
9th Jul 2020, 5:52 AM
James Clark I. Vinarao
James Clark I. Vinarao - avatar
+ 1
Obviously 1st part of your program will give error because myArr[1][1] means 2nd array's 2nd number which you didn't include in the declaration. 2nd part of your program will run because myArr[2][1] exist .It means 3rd array's 2nd number which is 6.So it gives output 6.
9th Jul 2020, 6:38 AM
The future is now thanks to science
The future is now thanks to science - avatar
+ 1
Kiibo ghayal, I agree too bro.
9th Jul 2020, 6:49 AM
Aman Pushp
Aman Pushp - avatar