+ 1

why there is an error

public class FirstLocalJava { public static void main(String[] args){ int[][] a = new int[2][]; a[0] = {1,2,3}; // why does the error occured? System.out.println(); } } why we must add new int[] to initialize the jagged array like a[0] = new int[]{}

2nd May 2021, 2:28 AM
Zhengrong Yan
Zhengrong Yan - avatar
3 Respuestas
+ 3
public class FirstLocalJava { public static void main(String[] args){ int[][] a = new int[2][1]; a[0][0] = 123; // why does the error occured? System.out.println(a[0][0]); } } //Are you expecting this ?
2nd May 2021, 3:23 AM
Atul [Inactive]
+ 2
David Yan Your initialisation is wrong. Why you must do new int[] {} to initialise because you are creating array of array so inner array should also be initialise, you cannot directly assign value because you must tell that you are creating array. It should be like this a[0] = new int[] {1, 2, 3}; https://code.sololearn.com/c2BC9pgG6f8M/?ref=app
2nd May 2021, 7:09 AM
A͢J
A͢J - avatar
+ 1
@Atul as you see on the code I want to create a jagged array and put another array into it. but I was told that I must write with new int[] or it doesn't work. I am just confused
2nd May 2021, 5:12 AM
Zhengrong Yan
Zhengrong Yan - avatar