Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double array initialization in Java

I was reading a book on Java and came across an example in which an array of type double was initialized in a way that I haven't seen before. What type of initialization is it and where else can it be used?

double m[][]={     {0*0,1*0,2*0,3*0},     {0*1,1*1,2*1,3*1},     {0*2,1*2,2*2,3*2},     {0*3,1*3,2*3,3*3} }; 
like image 298
Prateek Avatar asked Sep 02 '13 18:09

Prateek


People also ask

How do you initialize a double array in Java?

Here is how we can initialize a 2-dimensional array in Java. int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}, }; As we can see, each element of the multidimensional array is an array itself. And also, unlike C/C++, each row of the multidimensional array in Java can be of different lengths.

How do you initiate a double array?

On the other hand, to initialize a 2D array, you just need two nested loops. 6) In a two dimensional array like int[][] numbers = new int[3][2], there are three rows and two columns. You can also visualize it like a 3 integer arrays of length 2.

Can we initialize array two times?

No. The array is not being created twice. It is being created once and then it is being populated.

Can we declare a 2D array without column?

Note: When you initialize a 2D array, you must always specify the first dimension(no. of rows), but providing the second dimension(no. of columns) may be omitted.


2 Answers

This is array initializer syntax, and it can only be used on the right-hand-side when declaring a variable of array type. Example:

int[] x = {1,2,3,4}; String[] y = {"a","b","c"}; 

If you're not on the RHS of a variable declaration, use an array constructor instead:

int[] x; x = new int[]{1,2,3,4}; String[] y; y = new String[]{"a","b","c"}; 

These declarations have the exact same effect: a new array is allocated and constructed with the specified contents.

In your case, it might actually be clearer (less repetitive, but a bit less concise) to specify the table programmatically:

double[][] m = new double[4][4];  for(int i=0; i<4; i++) {     for(int j=0; j<4; j++) {         m[i][j] = i*j;     } } 
like image 99
nneonneo Avatar answered Sep 23 '22 00:09

nneonneo


You can initialize an array by writing actual values it holds in curly braces on the right hand side like:

String[] strArr = { "one", "two", "three"}; int[] numArr = { 1, 2, 3}; 

In the same manner two-dimensional array or array-of-arrays holds an array as a value, so:

String strArrayOfArrays = { {"a", "b", "c"}, {"one", "two", "three"} }; 

Your example shows exactly that

double m[][] = {     {0*0,1*0,2*0,3*0},     {0*1,1*1,2*1,3*1},     {0*2,1*2,2*2,3*2},     {0*3,1*3,2*3,3*3} }; 

But also the multiplication of number will also be performed and its the same as:

double m[][] = { {0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9} }; 
like image 30
SGal Avatar answered Sep 22 '22 00:09

SGal