2

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

2
  • 1
    The exampleStr variable 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. Commented Aug 10, 2019 at 20:51
  • you may think about accepting an answer now ;) Commented Aug 14, 2019 at 17:29

3 Answers 3

1

From my understanding, you are first declaring a 1-dimensional array exampleStr[]. Then, you are creating a 2-dimensional array, but are subscripting it with a 0, i.e., you are selecting the array at index 0, the array containing the null elements.

exampleStr[0][0] => with the first [0] you are selecting the first element at index 0, a null type. The second [0] would be called on that element, which is a null type and therefore not valid.

Essentially, you are not creating a 2-dimensional array in the first place.

Change your code to this and it will work:

public static void main(String args[]) {
    String exampleStr[][] = new String[][]
            {
                    {null,null,null},
                    // creates a 1-d String[], -> {"a", "b", "c"} is enough
                    new String[] {"a","b","c"},
                    // creates an array containing an empty string, -> {""} would be equivalent
                    {new String()} 

            };

    String exampleStr3[] = {null};

    String value = exampleStr[0][0];

    System.out.println(exampleStr.length);

    System.out.println(value);
}

EDIT: I added answers to the questions in the comments of the above code segment.

Sign up to request clarification or add additional context in comments.

4 Comments

You mean to say that, it is possible for us to pass a M-D array to a 1-D array ? From this example, I am creating a 1-D array, array[] and assigning it a value of arrays ? If that is the case, how would I then be able to access the string array "a","b","c" ? When I tried exampleStr[1] I got an array out of bounds error. If I were to change it to exampleStr[][], I am able to access the "a" using exampleStr[1][0]
Not exactly. During an assignment statement, e.g., String a = "a"; everything on the right side of the = is evaluated first. In your example, you are first creating a 2-d array, but are then selecting one of the arrays in your 2-d array. This selection, is a 1-d array, which then gets assigned to your exampleStr[]. String exampleStr[][] = { {"a", "b"} , {"c", "d"} }; // this assings a 2-d array You can then select one of the 2 arrays within by exampleStr[0] // selects {"a", "b"} or exampleStr[1] // selects {"c", "d"}.
In your example, you are selecting one of the arrays in your 2-d array, BEFORE the assignment, which is correct in your case, since you declared exampleStr[] as a 1-d array, which has to be initialized with a 1-d array. In your case, you selected the array at position 0: {null, null, null} by writing [0] at the end of your 2-d array, thus you assign only one of the arrays, the one containing the null values, to exampleStr[]. Since this is a 1-d array, you can select one of the elements with exampleStr[index], but can't further index into it, because you have selected a null element.
Further, you cannot index a null element or a string element using [index]. For a string, you'd have to call a method, such as charAt(index), e.g., String a = "abc"; => a.charAt(0); which would return the character at index 0, which is a. I hope that helps and sorry for the long comments :)
1

Your initial code meant that your create a 2-dimensionnal array but only keep the first box (using the [0] at the end), so you could read its first element with exampleStr[0] but exampleStr[0][0] is not possible because exampleStr[0] is not an array, so you can't access something into it using an index

String exampleStr[] = new String[][] 
  {
      {null,null,null}, 
      new String[] {"a","b","c"}, 
      {new String()} 
  }[0];

If we split it, it look slike

String array[][] = new String[][] 
  {
      {null,null,null}, 
      new String[] {"a","b","c"}, 
      {new String()} 
  };
String exampleStr[] = array[0]; // which is the {null,null,null} part

Details for the 2-dim array and the details into it:

First, to get it working, exampleStr should be a 2-dimensionnal array with [][]

So there double [] so it's a 2 dimensionnal array of type String, which means, that you have an outer array, and each box can contain an (inner) array of String

Here you have, for each box of the outer array:

  1. {null, null, null} an array of three times the null element
  2. new String[]{"a", "b", "c"} an array of 3 String, can be reduced in {"a", "b", "c"}
  3. {new String()} an array of one empty String, same as {""}

    String[][] exampleStr = new String[][]{
            {null, null, null},
            new String[]{"a", "b", "c"}, // not sure what this mean
            {new String()} // not sure of this too
    };
    

Then exampleStr[0][0] means accessing the first element of the first box

10 Comments

I don't agree with your first statement. Leave exampleStr as a 1-D array and don't try to use as a 2-D one, and things will work just fine. I think that this is an exercise to get the OP to understand the difference between a 1-D and 2-D array, and how rows of a 2-D array are 1-D arrays themselves.
Why should it be a two-dimensional array? You don't know what the example was trying to show.
You still might want to remove the erroneous first part of your answer, as pointed out by both @JamesKPolk and myself.
@HovercraftFullOfEels I've changed the order, to only talk the 2-dim part as a supplement
OK, I suppose that's better
|
0

Wow, that's a weird example, where did you find such a thing? I believe what is going on is that exampleStr is actually a one-dimensional array, so there is no exampleStr[0][0].

To start with there are not really multi-dimensional arrays in Java as there are in languages like C#, but there are arrays of arrays. The curly bracket syntax is a way of initializing a data structure.

String exampleStr[] = new String[][] // This declares an array of arrays.
      {
          {null,null,null}, // first column values
          new String[] {"a","b","c"}, // second column values
          {new String()} // empty string is only element added to third column

      }[0]; // This initializes exampleStr to the first column values above.

exampleStr is a one-dimensional array of length 3, whose elements are null, null, and null. You would access those values as exampleStr[0], exampleStr[1], and exampleStr[2]. Hope this helps!

2 Comments

Thanks, Found it in a Java exercise book, the example wanted to know the output of exampleStr[0] which is null. I was not able to understand what was happening with the declaration because when I tried to access the "a" using String value = exampleStr[1][0]; I got the error array required, but String found , Would the value "a","b", "c" be accessible in this code ?
You're initializing a 1-d array with the first column, (column 0) of a 2-d array. To access 'a', 'b', or 'c', you'd have to initialize exampleStr[] = new String[][]{ ... }[1].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.