I was coding some sample examples of Java questions on Multi-dimensional arrays to get an understanding on its initialization and accessibility. I copied the code syntax as in the example but am not able to understand the how to decode the code.
Following the example, I tried to get an understanding on the initialization of the multi-dimensional array. I couldn't grasp the syntax logic and made just one change to the code to test my understanding, the example was initially to get the output of String value = exampleStr[0];. I changed it to String value = exampleStr[0][0]; which gave out the error.
public class MyClass {
public static void main(String args[]) {
String exampleStr[] = new String[][]
{
{null,null,null},
new String[] {"a","b","c"}, // not sure what this mean
{new String()} // not sure of this too
}[0];
// what does the whole block actually mean in a compiler/logic sense ?
String exampleStr3[] = {null};
// this is where the compiler error came!
String value = exampleStr[0][0];
// shows 3 for this code when error line is commented out
System.out.println(exampleStr.length);
System.out.println(value);
}
}
In the example, the syntax is String value = exampleStr[0]; which outputs null, I changed it to String value = exampleStr[0][0]; and got the error.
Why am I getting the error and could someone explain to me the behavior of the code/compiler in regards to this code's syntax. How is the array structure
exampleStrvariable is a one-dimensional String array, and so it makes no sense to the Java compiler (and to me) you're trying to use it as if it were a 2-dimensional array.