470

Consider:

int[][] multD = new int[5][];
multD[0] = new int[10];

Is this how you create a two-dimensional array with 5 rows and 10 columns?

I saw this code online, but the syntax didn't make sense.

payne
  • 4,691
  • 8
  • 37
  • 85
AppSensei
  • 8,270
  • 22
  • 71
  • 99

13 Answers13

868

Try the following:

int[][] multi = new int[5][10];

... which is a short hand for something like this:

int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];

Note that every element will be initialized to the default value for int, 0, so the above are also equivalent to:

int[][] multi = new int[][] {
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

... or, more succinctly,

int[][] multi = {
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
obataku
  • 29,212
  • 3
  • 44
  • 57
  • 27
    The fun part is you can have different columns in different rows as well. For example:- int[][] multi = new int[5][]; multi[0] = new int[10]; multi[1] = new int[6]; multi[2] = new int[9] is also perfectly valid – JavaTec Mar 09 '16 at 21:25
  • @JavaTec if we want to hardcode the value, with different column, how should we do that ?? – John Sick Aug 28 '16 at 04:46
  • 2
    Hi Muneeb, if i understood correctly, you're asking in a multi-dimensional array, with different column size for each row, how to assign the values. Here'z how: int[][] multi = new int[][]{{1,2,3},{1,2,3,4},{1}}; and you can access/print them like: for(int i=0; i – JavaTec Aug 31 '16 at 17:39
  • 2
    Do we need to use `new int[][]` in `=new int[][]{...}` variant? Can we just write `={...}`? – Nawaz May 25 '17 at 07:56
  • 2
    @Nawaz No, Arrays are Object in java and memory is allocated to Objects only by using `new` keyword. – roottraveller Jun 13 '17 at 09:40
  • 1
    @Oldrinb what about `int array[][] = new int[3][];` VS `int array[][] = new int[][3];` ?? which one is legal as I have read both version somewhere. – roottraveller Jun 13 '17 at 09:40
  • Can we also call it 5 columns and 10 rows? – Harsha Apr 21 '18 at 15:58
  • 2
    @roottraveller that’s wrong, you can [just write `int[][] multi = { { … }, … };`](https://ideone.com/RjxQw7) Being an object does not imply that writing `new` was the only way to create an object. `String s = "123";` also doesn’t require the `new` keyword. – Holger Feb 10 '23 at 13:28
  • 3
    @Nawaz a bit late but since the previous reply was just wrong, I want to emphasize that you *can* write `… = { … }`. E.g. https://ideone.com/RjxQw7 – Holger Feb 10 '23 at 13:30
85

We can declare a two dimensional array and directly store elements at the time of its declaration as:

int marks[][]={{50,60,55,67,70},{62,65,70,70,81},{72,66,77,80,69}};

Here int represents integer type elements stored into the array and the array name is 'marks'. int is the datatype for all the elements represented inside the "{" and "}" braces because an array is a collection of elements having the same data type.

Coming back to our statement written above: each row of elements should be written inside the curly braces. The rows and the elements in each row should be separated by a commas.

Now observe the statement: you can get there are 3 rows and 5 columns, so the JVM creates 3 * 5 = 15 blocks of memory. These blocks can be individually referred ta as:

marks[0][0]  marks[0][1]  marks[0][2]  marks[0][3]  marks[0][4]
marks[1][0]  marks[1][1]  marks[1][2]  marks[1][3]  marks[1][4]
marks[2][0]  marks[2][1]  marks[2][2]  marks[2][3]  marks[2][4]


NOTE:
If you want to store n elements then the array index starts from zero and ends at n-1. Another way of creating a two dimensional array is by declaring the array first and then allotting memory for it by using new operator.

int marks[][];           // declare marks array
marks = new int[3][5];   // allocate memory for storing 15 elements

By combining the above two we can write:

int marks[][] = new int[3][5];
informatik01
  • 16,038
  • 10
  • 74
  • 104
Indu Joshi
  • 851
  • 6
  • 4
53

You can create them just the way others have mentioned. One more point to add: You can even create a skewed two-dimensional array with each row, not necessarily having the same number of collumns, like this:

int array[][] = new int[3][];
array[0] = new int[3];
array[1] = new int[2];
array[2] = new int[5];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97
  • 5
    Well said! This is the most important aspect of having independent initialization. – Ahamed Dec 24 '13 at 19:00
  • 2
    @Victor what about `int array[][] = new int[3][];` VS `int array[][] = new int[][3];` ?? which one is legal as I have read both version somewhere. – roottraveller Jun 13 '17 at 09:39
30

The most common idiom to create a two-dimensional array with 5 rows and 10 columns is:

int[][] multD = new int[5][10];

Alternatively, you could use the following, which is more similar to what you have, though you need to explicitly initialize each row:

int[][] multD = new int[5][];
for (int i = 0; i < 5; i++) {
  multD[i] = new int[10];
}
João Silva
  • 89,303
  • 29
  • 152
  • 158
  • 3
    Also realize that only primitives do not require initialization. If you declare the array as `Object[][] ary2d = new Object[5][10];` then you still must initialize each element of the 2D array. – Armand Mar 05 '14 at 00:28
  • 3
    Unless you handle the `null` case safely for any non primitives. Whether or not you should initialize each element is completely dependent on your design. Also, just to clarify - primitives cannot be null and get instantiated to a defined default value if not assigned one by you. E.g. an `int` cannot be null and when you say `int i;` without assigning a value, the default one of `0` is used. [Read about it here](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) – indivisible May 03 '14 at 05:21
  • One further clarification, default values are only handed out to class/instance variables. Local variables (inside methods) must be manually initialized before use. – indivisible May 03 '14 at 05:33
12

It is also possible to declare it the following way. It's not good design, but it works.

int[] twoDimIntArray[] = new int[5][10];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ctomek
  • 1,696
  • 16
  • 35
9

Try:

int[][] multD = new int[5][10];

Note that in your code only the first line of the 2D array is initialized to 0. Line 2 to 5 don't even exist. If you try to print them you'll get null for everyone of them.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
8

In Java, a two-dimensional array can be declared as the same as a one-dimensional array. In a one-dimensional array you can write like

  int array[] = new int[5];

where int is a data type, array[] is an array declaration, and new array is an array with its objects with five indexes.

Like that, you can write a two-dimensional array as the following.

  int array[][];
  array = new int[3][4];

Here array is an int data type. I have firstly declared on a one-dimensional array of that types, then a 3 row and 4 column array is created.

In your code

int[][] multD = new int[5][];
multD[0] = new int[10];

means that you have created a two-dimensional array, with five rows. In the first row there are 10 columns. In Java you can select the column size for every row as you desire.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zishan
  • 613
  • 8
  • 12
8
int [][] twoDim = new int [5][5];

int a = (twoDim.length);//5
int b = (twoDim[0].length);//5

for(int i = 0; i < a; i++){ // 1 2 3 4 5
    for(int j = 0; j <b; j++) { // 1 2 3 4 5
        int x = (i+1)*(j+1);
        twoDim[i][j] = x;
        if (x<10) {
            System.out.print(" " + x + " ");
        } else {
            System.out.print(x + " ");
        }
    }//end of for J
    System.out.println();
}//end of for i
reixa
  • 6,903
  • 6
  • 49
  • 68
Kieran Horton
  • 81
  • 1
  • 1
7
int rows = 5;
int cols = 10;

int[] multD = new int[rows * cols];

for (int r = 0; r < rows; r++)
{
  for (int c = 0; c < cols; c++)
  {
     int index = r * cols + c;
     multD[index] = index * 2;
  }
}

Enjoy!

Albeoris
  • 109
  • 1
  • 7
4

Try this way:

int a[][] = {{1,2}, {3,4}};

int b[] = {1, 2, 3, 4};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
4

These types of arrays are known as jagged arrays in Java:

int[][] multD = new int[3][];
multD[0] = new int[3];
multD[1] = new int[2];
multD[2] = new int[5];

In this scenario each row of the array holds the different number of columns. In the above example, the first row will hold three columns, the second row will hold two columns, and the third row holds five columns. You can initialize this array at compile time like below:

 int[][] multD = {{2, 4, 1}, {6, 8}, {7, 3, 6, 5, 1}};

You can easily iterate all elements in your array:

for (int i = 0; i<multD.length; i++) {
    for (int j = 0; j<multD[i].length; j++) {
        System.out.print(multD[i][j] + "\t");
    }
    System.out.println();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ritesh9984
  • 418
  • 1
  • 5
  • 17
2

Actually Java doesn't have multi-dimensional array in mathematical sense. What Java has is just array of arrays, an array where each element is also an array. That is why the absolute requirement to initialize it is the size of the first dimension. If the rest are specified then it will create an array populated with default value.

int[][]   ar  = new int[2][];
int[][][] ar  = new int[2][][];
int[][]   ar  = new int[2][2]; // 2x2 array with zeros

It also gives us a quirk. The size of the sub-array cannot be changed by adding more elements, but we can do so by assigning a new array of arbitrary size.

int[][]   ar  = new int[2][2];
ar[1][3] = 10; // index out of bound
ar[1]    = new int[] {1,2,3,4,5,6}; // works
inmyth
  • 8,880
  • 4
  • 47
  • 52
0

If you want something that's dynamic and flexible (i.e. where you can add or remove columns and rows), you could try an "ArrayList of ArrayList":

public static void main(String[] args) {

    ArrayList<ArrayList<String>> arrayListOfArrayList = new ArrayList<>();

    arrayListOfArrayList.add(new ArrayList<>(List.of("First", "Second", "Third")));
    arrayListOfArrayList.add(new ArrayList<>(List.of("Fourth", "Fifth", "Sixth")));
    arrayListOfArrayList.add(new ArrayList<>(List.of("Seventh", "Eighth", "Ninth")));
    arrayListOfArrayList.add(new ArrayList<>(List.of("Tenth", "Eleventh", "Twelfth")));

    displayArrayOfArray(arrayListOfArrayList);
    addNewColumn(arrayListOfArrayList);
    displayArrayOfArray(arrayListOfArrayList);
    arrayListOfArrayList.remove(2);
    displayArrayOfArray(arrayListOfArrayList);
}

private static void displayArrayOfArray(ArrayList<ArrayList<String>> arrayListOfArrayList) {
    for (int row = 0; row < arrayListOfArrayList.size(); row++) {
        for (int col = 0; col < arrayListOfArrayList.get(row).size(); col++) {
            System.out.printf("%-10s", arrayListOfArrayList.get(row).get(col));
        }
        System.out.println("");
    }
    System.out.println("");
}

private static void addNewColumn(ArrayList<ArrayList<String>> arrayListOfArrayList) {
    for (int row = 0; row < arrayListOfArrayList.size(); row++) {
        arrayListOfArrayList.get(row).add("added" + row);
    }
}

Output:

First     Second    Third     
Fourth    Fifth     Sixth     
Seventh   Eighth    Ninth     
Tenth     Eleventh  Twelfth   

First     Second    Third     added0    
Fourth    Fifth     Sixth     added1    
Seventh   Eighth    Ninth     added2    
Tenth     Eleventh  Twelfth   added3    

First     Second    Third     added0    
Fourth    Fifth     Sixth     added1    
Tenth     Eleventh  Twelfth   added3    
Scott Deagan
  • 331
  • 3
  • 8