Published March 07, 2018 by

2 dimensional Array in java

2 dimensional Array in java

In this post, we will mainly deal with 2D array.

What is 2D Array?

  • An array of arrays is known as 2D array.
  • The two dimensional (2D) array in java is also known as matrix.
  • A matrix can be represented as a table of rows and columns.

How to declare 2D Array?

The syntax is as follows:-

Declaration of 2D Array:-

DataType[][] arraryName = new DataType[rowCount][columnCount];
String[][] twoDArray = new String[3][2];

Here, twoDArray is a two-dimensional (2d) array. The array can hold maximum of 6 elements of type String.

Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and not 1.

Initialization of 2D Array:-

arrayName[rowCount][columnCount] = value;
twoDArray[0][0] = "Value";

Lets have a look at the following java program

public class TwoDArray 
           public static void main(String[] args) 
                      String[][] arr = new String[3][2];
                      arr[0][0] = "UserName_1";
                      arr[0][1] = "Password_1";
                      arr[1][0] = "UserName_2";
                      arr[1][1] = "Password_2";
                      arr[2][0] = "UserName_3";
                      arr[2][1] = "Password_3";

                       for (int i = 0; i < 3; i++)
                                 for (int j = 0; j < 2; j++)
                                           System.out.println("Value for arr["+i+"]["+j+"] :- "+ arr[i][j]);



Value for arr[0][0] :- UserName_1
Value for arr[0][1] :- Password_1
Value for arr[1][0] :- UserName_2
Value for arr[1][1] :- Password_2
Value for arr[2][0] :- UserName_3
Value for arr[2][1] :- Password_3

When we are using 2D Array in Selenium?

We use 2D array to store data as a matrix or in the form of row and column. In order to perform Data driven testing, we use @DataProvider Annotation. We may use 2D Array to supply Test data sets to Test Method.

Refer below program to understand how exactly 2D Array has implemented in selenium to provide a data from excel file:-

public String[][] dataProvider()
           FileInputStream file = new FileInputStream(TESTDATA_SHEET_PATH);
           Workbook book = WorkbookFactory.create(file);
           Sheet sheet = book.getSheet("SheetName");
           String[][] data = new String[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
           for (int i = 0; i < sheet.getLastRowNum(); i++)
                 for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++)
                          data[i][k] = sheet.getRow(i + 1).getCell(k).toString();

          return data;

Popular Posts