Array declaration
One dimensional array declaration
import java.lang.*;
class Test {
public static void main(String[] args) {
int[] x; // VALID AND RECOMMENDED as name is clearly separated from type
int []x; // VALID
int x[]; // VALID
}
}
Declaring array with set size:
import java.lang.*;
class Test {
public static void main(String[] args) {
int[6] x; // INVALID: cannot specify size at declaration, compile-time error
int[] y; // VALID
}
}
Two dimensional array declaration
import java.lang.*;
class Test {
public static void main(String[] args) {
int[][] x; // VALID
int [][]y; // VALID
int z[][]; // VALID
int[] []a; // VALID
int[] b[]; // VALID
int []c[]; // VALID
}
}
Three dimensional array declaration
import java.lang.*;
class Test {
public static void main(String[] args) {
int[][][] a; // VALID
int [][][]b; // VALID
int[] [][]c; // VALID
int[] d[][]; // VALID
int[] []e[]; // VALID
int[][] []f; // VALID
int g[][][]; // VALID
int[][] h[]; // VALID
int [][]i[]; // VALID
int []j[][]; // VALID
}
}
Array declaration conclusion
import java.lang.*;
class Test {
public static void main(String[] args) {
int[] x,y; // VALID: both x and y are one dimensional arrays
int[] a[],b; // VALID: a is two dimensional and b is one dimensional
int[] c[],d[]; // VALID: both c and d are two dimensional arrays
int[] []e,f; // VALID: both e and f are two dimensional arrays, space between the brackets is ignored by compiler
int[] []g,h[]; // VALID: g is a two dimensional array and h is a three dimensional array
int[] []i,[]j; // INVALID: j is invalid, dimension before variable is only allowed for first variable, compile-time error
int[6] x; // INVALID: cannot specify size at declaration, compile-time error
}
}
When declaring dimension before the variable, it is only allowed for the first variable in a declaration.
Size of array cannot be specified at declaration