interface MyInterface{} MyInterface arr[];
abstract class MyAbstract{} MyAbstract arr[];
Java provides two types of array-
arrayType[] arrayReferenceVariable; (or) arrayType []arrayReferenceVariable; (or) arrayType arrayReferenceVariable[];
Example of array declaration- int scores[];
You cannot write the size of array in an array declaration, doing so will give compile-time error. Eg- int arr[5]; will give compile-time error.
arrayReferenceVariable = new arrayType[size];
Example of array instantiation- scores = new int[6];
You know that array is an object that is why it is instantiated with the new keyword. If you forget to specify the size of the array then you will get compile-time error.
arrayType[] arrayReferenceVariable = new arrayType[size]; (or) arrayType []arrayReferenceVariable = new arrayType[size]; (or) arrayType arrayReferenceVariable[] = new arrayType[size];
arrayType[] arrayReferenceVariable = {value1, value2, ..., valuen}; (or) arrayType[] arrayReferenceVariable = new arrayType[]{value1, value2, ..., valuen};
class Example { public static void main(String args[]) { int i = new int[3]; i[0] = 5; i[1] = 10; i[2] = 15; for(int j=0; j<i.length; j++) { System.out.println(i[j]); } } }
Output
5 10 15
arrayType[][] arrayReferenceVariable; (or) arrayType [][]arrayReferenceVariable; (or) arrayType arrayReferenceVariable[][]; (or) arrayType[] arrayReferenceVariable[]; (or) arrayType []arrayReferenceVariable[];
Example of multidimensional array declaration- int matrix[][];
You cannot write the size of array in an array declaration, doing so will give compile-time error. Eg- int matrix[3][3]; will give compile-time error.
arrayReferenceVariable = new arrayType[rowsize][columnsize];
Example of array instantiation- matrix = new int[3][3];
Here, we will obtain a multidimensional array matrix having 3 rows and 3 columns. With the help of new keyword, you instantiate multidimensional array. If you forget to specify the size of row and column then you will get compile-time error.
arrayType[][] arrayReferenceVariable = new arrayType[rowsize][columnsize]; (or) arrayType [][]arrayReferenceVariable = new arrayType[rowsize][columnsize]; (or) arrayType arrayReferenceVariable[][] = new arrayType[rowsize][columnsize]; (or) arrayType[] arrayReferenceVariable[] = new arrayType[rowsize][columnsize]; (or) arrayType []arrayReferenceVariable[] = new arrayType[rowsize][columnsize];
int[][] matrix = {{12, 13, 14}, {47, 34, 65}}; // This will create 2x3 multidimensional array int[][] matrix = new int[][]{{12, 13, 14}, {47, 34, 65}}; // This will also create 2x3 multidimensional array
class Example { public static void main(String args[]) { int x[][]={{1,2,3},{5,6,7},{8,9,10}}; for(int a=0; a<3; a++) { for(int b=0; b<3; b++) { System.out.println(x[a][b]+" "); } System.out.println(); } } }
Output
1 2 3 5 6 7 8 9 10