Reputation: 1
I am not able to understand why I have to mention the data type of the 2d array again and again if declared it as a class variable:
public class DDR
{
int[][] arr;
int m;
int n;
public DDR() {
m=0;
n=0;
int arr[][] = new int[m][n];
}
}
When I omit int
, it says "it's not a statement."
Upvotes: 0
Views: 413
Reputation: 421
The int arr [] []
phrase in your constructor is actually declaring a new array that shadows your field. Remember that arrays are variables, too. Omitting the int
makes a statement that syntactically makes no sense. In this case, what you want is to assign an array to your field arr
of type int[][]
.
arr = new int[m][n];
Upvotes: 1
Reputation: 114230
Right now, arr
in the constructor is not a class variable, but rather a local variable that is shadowing the class variable. Both int
and [][]
are part of the type.
To initialize the class variable, don't declare a new variable. You must omit both the element type (int
) and the array portion of the declaration ([][]
). Also, m
and n
have default values of zero, so you may want to set them before allocating the arrays:
m = 1;
n = 1;
arr = new int[m][n];
Upvotes: 2