Home>

Excuse me for a rudimentary question.
About a class that outputs a table of numbers in a two-dimensional array.

package info.searchman;
public class Practice
{
    public static void main (String [] args)
    {
        int kuku [] [] = new int [9] [];
        for (int i = 0;i<9;i ++)
        {
            kuku [i] = new int [9];
            for (int j = 0;j<9;j ++)
                kuku [i] [j] = (i + 1) * (j + 1);
        }

        // assign values ​​to the array kuku
        for (int i = 0;i<9;i ++)
        {
            for (int j = 0;j<9;j ++)
                System.out.printf ("% 2d", kuku [i] [j]);
            System.out.println ();
        }
    }
}

Question ①
Does the following statement declare 9x9 and that the last parenthesis is optional?

  

int kuku [] [] = new int [9] [];

Question point ②
Why is the following sentence necessary?

  

kuku [i] = new int [9];

  • Answer # 1

    What you have to do isJava so-called 2D arrays are "arrays of arrays".
    For example, suppose you create an Object type array like this:

    Object [] objs = new Object [3];

    This is essentially the same if you write: ()

    Object [] objs = {null, null, null};

    The same is true if you create an array of type int [], and the following two codes have the same meaning.

    int [] [] arr = new int [3] [];
    int [] [] arr = {null, null, null};

    : When I tried it at hand, the bytecode was different.


      

    Question point ②
      Why is the following sentence necessary?

      
        

    kuku [i] = new int [9];

      

    All elements are null, so you need to create an array object before accessing the elements.

      

    Question ①
      Does the following statement declare 9x9 and that the last parenthesis is optional?

      
        

    int kuku [] [] = new int [9] [];

      

    Not 9x9. A 9-element int [] type array is generated.


    The following should work without any problem. This may be more intuitive.

    // ↓ As I wrote in the previous answer, [] is generally attached to the type
    int [] [] kuku = new int [9] [9];

    In this case, kuku [i] = new int [9];is unnecessary.

  • Answer # 2

    Because you don't understand the basics of Java in the first place, let's learn about that first.

    If you answer here, it will be meaningless for you