You are here:   HomeJava ProgrammingJava ArrayInitialization of Two Dimensional Arrays Java
by Dinesh Thakur Category: array

Like one dimensional array, one can also initialize multidimensional array when they are declared. For example: A two-dimensional array table with 2 rows and 3 columns can be declared and initialized as follows,

int table[] [] = {{1,2,3},{3,4,5}};

Note that each array row is initialized separately by enclosing them within its own set of curly braces. Moreover, there must be a comma at the end of each row except for the last one. Within each row, the first value will be stored in the first position of the sub array, the second value will be stored in the second position and so on.

Now let us consider a program to calculate sum of elements of each row in two dimensional array.

public class SumRC
{
      public static void main(String [] args)
    {
           int[] [] num = {{7,6,5},{4,5,3}};
           int i,j,sumRow,sumCol;
           for( i=0; i<num.length; i++)
               {
                   sumRow = 0;
                   for (j=0; j<num[i].length;j++)
                        {
                               sumRow += num[i][j];
                               System.out.print( num[i] [j] + "  ");
                        }
                               System.out.println("---  " + sumRow);
          
                }
                  System.out.println("-------------------------- ");
                  for(i=0; i<num[0].length; i++)
                      {
                          sumCol = 0;
                          for( j=0; j<num.length; j++)
                              sumCol += num[j] [i];
                              System.out.print(sumCol + "  ");
                      }
      }
}

Initialization of Two Dimensional Arrays Java



Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article