2

For some reason, in IntelliJ (if that matters), when I try to initialize my 2D arrays, only the first box gets initialized for the size that I am specifying. i.e. int[][] grid = new int[9][9]; and when I run through with the debugger, it shows that I've created an array that is int[9][]. Does anyone know what I am doing wrong? could it be that I need to update something? anything helps. Thank you.

3
  • 3
    The debugger is showing that grid is an int[9][], i.e. an array of length 9 of int arrays. Each of the 9 subarrays can have different lengths, so the debugger cannot show anything for the second []. Commented Sep 18, 2020 at 22:36
  • 2
    Java doesn't really have 2D arrays. What you have is an array that contains arrays. You'll have to initialize each of the arrays in your array separately, for example in a for loop. Commented Sep 18, 2020 at 22:38
  • What you are doing wrong is having the wrong expectation for how arrays work. You cannot make an array that contains 9 int[9]s, because int[9] is not a type, int[] is. Commented Sep 18, 2020 at 23:06

3 Answers 3

3

It is just a debugger representation.

It always works fine.
It do create a two dimensional array in memory.

public static void main(String[] args) {
    int[][] grid = new int[9][9];

    System.out.println(grid.length);
    System.out.println(grid[0].length);
}

This code will always return dimensions properly as:

9
9

What you might get in a debugger is something like this - where definitely is not written int[9][9] what you are expected, however this is a representation only - there is nothing with correctness. enter image description here

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

Comments

0

I've had exactly the same problem and I've found @Misho Zhghenti's answer is the best! Yes, IntelliJ's representation in debug leads to confusion. A multidimensional array in Java isn't really like that, is just an array of arrays.

Thank you @EthanB21 @Misho Zhghenti

Comments

-1

Please post complete code, what exactly you have written and debugging.

Restart your IDE and check once with below code.

public static void main(String[] args) {
    int[][] grid = new int[9][9];
    int value = 10;
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            grid[i][j] = ++value;
        }
    }

    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            System.out.print(((j == 0) ? "" : ", ") + grid[i][j]);
        }
        System.out.println();
    }
}

Note: IDE may misbehave too or might be responding late.

Comments

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.