# Assigning Values to Multi Array

• April 17th, 2011, 09:29 PM
dredjohn
Assigning Values to Multi Array
Hi,

I'm new to Java programming, and trying to thoroughly understand multidimensional arrays and how they work.

If I entered the following, it appears the following multi array (table) would be created:

int[][] table = {{44,22,43},
{55,39,88},
{92,40,99}};

----------------
| 44 | 22 | 43 |
---------------
| 55 | 39 | 88 |
---------------
| 92 | 40 | 99 |
---------------

Then if I later called:

System.out.println(table[0][2]);

This would print out row 1, column 3: 43.

Another option (to do the same thing):

int[][] table = new int[3][3];

Then, I could assign an array to a variable, like this:

int[] t0 = { 44, 22, 43 };
int[] t1 = { 55, 39, 88 };
int[] t2 = { 92, 40, 99 };

...and I could then assign each variable to my original array like this:

table[0] = t0;
table[1] = t1;
table[2] = t2;

I have 2 questions:
1. Is there an advantage to either approach?
2. With the latter approach I've tried assigning the arrays directly to the original variable without success. For example:

table[0] = { 44, 22, 43 };

This produces an error though (i.e. Illegal start of expression). Is there a reason I need to create temp variables for each array before adding it to the main array (i.e. table)?

Thanks
• April 17th, 2011, 11:45 PM
helloworld922
Re: Assigning Values to Multi Array
Directly initializing an N-d array can only be done when the array is first declared.

Code Java:

```int a[] = {1,2,3}; // understood implicitly as int a[]= new int[]{1,2,3}; int b[]; b = new int[]{1,2,3};```

It depends on the application. If you know what values you're going to put into an array already, why bother splitting it up into multiple statements? On the other hand, sometimes you don't know what's suppose to be in each row, so you'd use the second approach. The second method also lets you produce jagged arrays (arrays where different rows can have different widths).
• April 18th, 2011, 07:09 PM
dredjohn
Re: Assigning Values to Multi Array
Gotcha - thanks!
• April 18th, 2011, 07:43 PM
helloworld922
Re: Assigning Values to Multi Array
Hmm, I must have been tired when I posted that (and/or crazy), but either method can actually be used to create jagged arrays. However, the other info should be accurate.