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} };
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.
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.
No. The array is not being created twice. It is being created once and then it is being populated.
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.
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; } }
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} };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With