how can i declared two dimension array in java
yes u can int[][] a=new int[M][N];
or the alternative, like: ``` int[][] storeHours = { { 9, 5 }, {10, 9}, {6, 11} }; System.out.println("on monday, the store is open from " + storeHours[0][0] + "am to " + storeHours[0][1] + "pm."); System.out.println("tues it's open " + storeHours[1][0] + " to " + storeHours[1][1]); System.out.println("wednesday it's open " + storeHours[2][0] + " to " + storeHours[2][1]); System.out.println("==================================="); //now I'll loop through all the hours in a systematic way for(int i = 0; i < storeHours.length; i++) { for(int ii = 0; ii < storeHours[i].length; ii++) { if(ii == 0) { System.out.print("On day " + (i+1) + ", the store is open from "); } System.out.print(storeHours[i][ii]); if(ii == storeHours[i].length-1) { System.out.print("."); //prints '.' if it's the last # in the row } else{ System.out.print("-"); //prints '-' if it's not the last # in the row } } System.out.println(""); //creates newline } ``` There I loop through the 2d array, so even if each row has an odd amount of columns, and there are hundreds of elements in the array, it should run smoothly.. Note that storeHours.length; will return the amount of rows in a 2d array, and storeHours[row #].length; will return the amount of columns in the specified row. and when you declare a 2d array, it's array[rows][columns]; not the other way around, so in the array I made, it has 3 rows, each with 2 columns. Below i'll attach the actual output of the program:
int[][] a; or String[][] str; or whatever datatype you need. You have asked for declaration. If you assign value, it is initialisation (e.g int[][] a = 0;)
Addendum: it can not be int[][] a = 0, because you need 2 values or two indices. Sorry, my bad.
Join our real-time social learning platform and learn together with your friends!