Arrays in Java and its implementation in WebDriver

Welcome back to Java Tutorial, In the last tutorial we have gone through the various type of variables that users can use in java. But in this tutorial, we are going to learn about Arrays in Java

This tutorial is going to cover the following topics

  • Definition
  • Type
  • Examples.

Definition:  Array is a data structure defined in java that can store data of the same type mainly primitive data and Class reference. Each Array has a size and it can’t take value more than the size of the array and if we need to access any element or data stored in the array at any point in time then we need to use the index of data in the array. So by using the index of data in the array, we can easily access the data.

Type of Array

One Dimensional Array: One-dimensional array is more like a list of the same kind of data. The creation of array and initialization is 3 steps process. So let’s see these steps

Step 1:  Array declaration: We have two ways to declare a one-dimensional array. First, we will see the syntax of the array, and then we will see the actual implementation.
First way:
<Data Type>  <array name> [];
Second way:
<Data Type>[]  <array name> ;

For example, we are going to declare an array of double value or an integer with variable name “firstExample”

double firstExample[];

Or
double[] firstDoubleArrray;

But the above lines are not going to create the memory for above-declared array and the array is having null as a value. So to create the memory in heap we need to call “new” operator. So let’s try our luck now.

Step 2: Array creation:  After declaring an array second step is to create an array just by allocating memory for it just with the help of “new ”operator,
See the syntax
<Data Type>  <name> [] = new <Data Type>[size of array];
So it will look like this:

int  intArray[] = new int[3];


Here intArray is the reference of Integer array and new int[3] is allocating memory to store 3 integer array. But if we are going to print each value stored in an array then it will print zero for each index of the array. So it means we don’t have any value assigned to the array.

 

     Step 3: Array initialization: After declaration and creation of array now the third step comes to initializing the value of the array. So again here we have two options to initialize it

First way:   Assign the value to each index one by one

intArray[0] =  12;   /* we have assigned integer value 12 to data element present at zero index means */

intArray[1] =  13; // here we have assigned  integer value 13 to element present at index 1

intArray[2] =  17;

Second way:  In this way, we need to put all value inside the curly bracket just separated by commas.

For example:
int  secondWay ={1,5,2,5,3};
here memory allocation would be done automatically.

Example:

So now let’s create one java class in which we would follow all the above-mentioned steps to create a Java array and will also print each value present on each index one by one.

Step1- Create one java class Array

Step 2- Select all code lines of code in your newly  created class and replace it with the following line of code

public class Array {

public static void main(String[] args) {

// Step 1: declaration:
int[] array;

// Step 2: Array creation:
array = new int[6];

// Step 3: Array initialization:
array[0] = 2;
array[1] = 3;
array[2] = 4;
array[3] = 5;
array[4] = 6;
array[5] = 7;

// Lets see how many elements are present in array
System.out.println("size of array is ===" + array.length);

// Printing individual value using index example lets print value
// present at 4th place that is having index 3

System.out.println("Value present on 4th place is " + array[3]);

// Printing all values of array using index
for (int i = 0; i <= 5; i++) {
System.out.println("Value sitted at index= " + i + " is "
+ array[i]);
}

// Second type of array initialization
int[] array1 = { 2, 4, 5, 6, 10, 12, 13 };
System.out.println("size of array is ===" + array1.length);

// example of taking the max value of interator i.e. the size of array
for (int j = 0; j < array1.length; j++) {
System.out.println("Value sitted at index= " + j + " is "
+ array1[j]);
}
}
}

In Console, the result would be something like this

size of array is ===6
Value present on 4th place is 5
Value sitted at index= 0 is 2
Value sitted at index= 1 is 3
Value sitted at index= 2 is 4
Value sitted at index= 3 is 5
Value sitted at index= 4 is 6
Value sitted at index= 5 is 7
size of array is ===7
Value sitted at index= 0 is 2
Value sitted at index= 1 is 4
Value sitted at index= 2 is 5
Value sitted at index= 3 is 6
Value sitted at index= 4 is 10
Value sitted at index= 5 is 12
Value sitted at index= 6 is 13

Multi-dimensional Array: Now you would be able to create a one-dimensional array. But think once again if you need to keep some inventory of a few things that you have, and then think about how it can be achieved. So just think one more minute….Oh, don’t worries let me help you out what we can do for that?
Scenario:

  1. Have you seen an excel sheet it’s a two-dimensional worksheet na, It contains row and Column. So again try your head, now you have any idea how to put all these things…Still itching your forehead then let me show you one visual
Product NameNumber leftInitial Count
Product 11230
Product 21015
Product 34345
Product x56100
Xy44444100000

Above is just the example of the two-dimensional array. But let’s imagine how this two-dimensional array has been created.

Just Imaging one-dimensional array in your mind and again assume that each compartment of the array is having another set of the array in each compartment. So are you able to see one tabular image or not and if yes, then you would be able to understand how two-dimensional array is coined? See the below image might be it will help you to understand it in a much better way

Arrays ExampllleDeclaring Multi-Dimensional Array: Multi-Dimensional array declaration is similar to a one-dimensional array.

Type name [][][]……..;

  1. Two dimensional Array of Double
    double productInventory [][]; or double [][] productInventory;
  2. Three dimensional Array of double
    double productInventory [][][]; double [][][] productInventory

So after going through both example, we would be able to see one symmetry i.e.  number of the square bracket is equal to the number in type of multi-Dimensional  that look like something like this
array <Number> Dimensional.

  1. Multi-Dimensional array creation: Again let’s follow the same process that you have used in a one-dimensional array, Creating memory by calling “new ” operator. So how it will look like
    Example:

    1. Two-dimensional array:
      //Declaration
      double productInventory [][];
      //Creating array by calling new operator.
      productInventory = new double[2][3];
    2. Three-dimensional array:
      //Declaration
      double productInventory [][][];
      //Creating array by calling new operator.
      productInventory = new double[2][3][5];
  • Initializing Multi-Dimensional Arrays: Taking example of Two dimensional Arraydouble productInventory [][] = {{2.3,3.4,2.6},{10.1,43.2,32.3}}
    Its means above is having two rows and 3 columns if you are taking it as two-dimensional matrix, So how we come to know the count of Row and Column
    So always remember:
    Row count = number of curly brackets inside the first curly bracket.
    Column count = the number of elements inside each curly bracket, So always remember we are keeping array inside each index of another array but some time number of the column might not be the same when you would be trying to create some irregular multidimensional arrays.

Example: Let’s see a complete example of Arrays in Java

1- Create one more java class TwoDimesionalExample

2- Select all line of code in newly created class except package and replace it with the following code and execute

public class TwoDimesionalExample {

    public static void main(String[] args) {

        // Step 1: declaration:
        int a[][] = null;
        // Step 2: Array creation:
        a= new int[2][2];
        
        // Step 3: Initialization:
        a[0][0] = 2;
        a[0][1] = 3;
        a[1][0] = 4;
        a[1][1] = 5;

        //Printing all values
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.println("Value sitted at index= " + i + j + " is  "
                        + a[i][j]);
            }
        }
        
        
        System.out.println("=============Second Example=========");
        //Second Example 

        int[][] b = { { 2, 4 }, { 3, 4 } };
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.println("Value sitted at index= " + i + j + " is  "
                        + b[i][j]);
            }

        }

}
}

Now friends lets see how to use Arrays in Java in Selenium Code:
Scenario:
1- We  know all expected options and we are going to store those values in Array and We are going to open dummy URL i.e. http://abodeqa.com/wp-content/uploads/2015/05/Dummy.html
2- We will use Select Class and will take control of Select Color drop-down and will fetch all options in a  List of WebElement and later we would iterate in the list and will fetch the text of each element one by one and will add it in another list of String type.
3- We will assert the expected array value with the list value.

Code:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;

public class DropDown {

    @Test
    public void test() {

        /*
         * Here we are assuming that following options should be present in
         * Color dropdown
         */
        String options[] = { "Select Color", "Red", "Green", "Yellow", "Grey" };

        // Opening dummy page and taking control of dropdown

        WebDriver driver = new FirefoxDriver();
        String url = "http://abodeqa.com/wp-content/uploads/2015/05/Dummy.html";
        driver.get(url);

        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        // Taking control on dropdown by calling Select class of Selenium
        // WebDriver Api

        Select select = new Select(driver.findElement(By.id("SelectID_One")));

        /*
         * fetching all webElements associated with each options by calling
         * getOptions() method of Select Class
         */

        List elements = select.getOptions();

        // Create one new array to store the text value of each webElement

        List optionsText = new ArrayList<>();

        /*
         * iterating in elements list and fetching text and inserting in
         * optionsText list
         */

        for (WebElement element : elements) {
            /*
             * getText() method is going to take out text of each element add()
             * method is adding all the text in optionsText in each iteration
             */
            optionsText.add(element.getText());
        }

        /*
         * here we have data in two data structure one is array and another is
         * in list so lets convert list in array by calling toArray() method
         */

        Assert.assertEquals(options, optionsText.toArray());

        System.out.println("Assertion passed");

        driver.quit();

    }

}


Cheat-sheet 
(Taken from Java Doc )

Arrays in Java

Dwarika Dhish Mishra

My name is Dwarika Dhish Mishra, its just my name and I am trying to bring the worth of my name in to actions and wants to be the solution not the problem. I believe in spreading knowledge and happiness. More over I am fun loving person and like travelling a lot. By nature I am a tester and a solution maker. I believe in the tag line of http://ted.org “Idea worth spreading” . For the same, I have created this blog to bring more and more learning to tester fraternity through day to day learning in professional and personal life. All contents are the part of my learning and so are available for all..So please spread the contents as much as you can at your end so that it could reach to every needful people in testing fraternity. I am pretty happy that more and more people are showing interest to become the part your Abode QA blog and I think this is good sign for us all because more and more content would be before you to read and to cherish. You may write or call me at my Email id: dwarika1987@gmail.com Cell: 9999978609

You may also like...

5 Responses

  1. Naman Singhal says:

    This post helped me out to get started with array understanding now I can play with array in java.

  2. Vishwa says:

    Hi

    Just go thru the Array code, explained very well, but In “DropDown” list code, line#54, for (WebElement element : elements) , getting the below error, please let me know the fix.

    Type mismatch: cannot convert from element type Object to WebElement

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.