ArrayList in Java with Examples

We are already aware that in Java, array size are of fixed-size. Meaning that we have to assign a size to an array, which we cannot increase or decrease.Therefore to change the size, we have to make a new array and copy the data that we want - which is inefficient and a painful technique.

To overcome this we can implement Arraylist in Java.

For more updates do like our Facebook page.

What is an ArrayList?
In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists
would increase in size when objects are added and shrinks as objects are removed similar to Dictionary object in VBscript.

We use ArrayList incase we are not sure on the upper bound on the number of elements. On the other side, a simple Array in java is a static data structure,
because the initial size of array cannot be changed, meaning it can be used only when the data has a known number of elements.

How to use it?
By calling the ArrayList constructor.

  1. ArrayList( ) -- An Array without any initial capacity
  2. ArrayList(Collection c) -- It creates a list containing the elements of the specified collection
  3. ArrayList(int capacity)--An Array with initial capacity

ArrayList Learn= new ArrayList();
ArrayList Learn= new ArrayList(10);

To create an array list in Java, we need declare an ArrayList variable (Learn) and call the ArrayList constructor to instantiate an ArrayList object and
assign it to the variable. We have taken 10 as the initial size of an Arraylist.
Arraylist Methods in Java
Methods in ArrayList

Adding Elements to Arraylist:-
We need to use the Add() method to add object(element) to the array list.


Incase we have specified a type of an Arraylist,the objects that we add via the add method must be of the correct type.
Arraylist of String type dont accept Int in java
Adding Int element to Arraylist of String Type

We can insert an object at a specific position in the list by listing the position in the add method

Learn.Add(1,"UFT"); //Thus index 1 have UFT in it .

Updating value of ArrayList:-
We need to use Set method for the same,

Learn.Set(0,"JavaScript")// we updated the index(0) to contain the value of "JavaScript" instead of "Java"

Deleting Elements in ArrayList:-
To remove all the elements, use the clear method:
To remove a specific element based on the index number, use the remove method:

Incase we don’t know the index of the object we want to remove, we can remove it by using the reference name,

Learn.remove(Selenium); //instead of using Learn.remove(0);

Count of elements in Arraylist:-
We call the size() method on the ArrayList instance. This returns the number of elements in the collection.

int iCnt = Learn.Size();

How to fetch element value from a given index:-
We use get() method, which receives the index of the element to get.

String value = Learn.get(0);

we can loop and iterate to get the value in each element of the arraylist.

Element sorting:-
Collections.sort. We can sort an ArrayList with this method.  This method sorts in ascending (low to high) order.



  • Creating ArrayList by using Add Method
  • Displaying ArrayList
  • Further using Index to Add elements into ArrayList 
  • Using Get Method
  • And getting the Size of Arraylist. 

import java.util.ArrayList;

public class LearnArrayList {
 public static void main(String[] args) {
  //Creating Arraylist
  ArrayList arrList = new ArrayList();
  //Adding Elements into Arraylist
  //Taking output of Arraylist
  System.out.println("Values in ArrayList ="+arrList);
  //Using Index to add Elements to ArrayList
  //Get method to fetch value at given index
  System.out.println("New Value at Index '1' ="+arrList.get(1));
  //Size of ArrayList
  System.out.println("Size = "+arrList.size());

Values in ArrayList =[Selenium, UFT, JAVA, VBSCRIPT]
New Value at Index '1' =QTP
Size = 5


  • Removing particular Element from Arraylist --Remove method 
  • Deleting all the elements of Arraylist--Clear method 

import java.util.ArrayList;

public class LearnArrayList {
 public static void main(String[] args) {
               //Creating String ArrayList of initial capacity of 3
  ArrayList<String> arrString = new ArrayList<String>(2);
  //add 4 elements
  //Remove particular element 
  System.out.println("New List after Remove="+arrString);
  //Clear the list
  System.out.println("Empty List"+arrString);

New List after Remove=[HTML, ANGULAR]
Empty List[]


  • Shuffle Arraylist elements
  • Sort Arraylist
  • Convert Arraylist into Array

import java.util.ArrayList;

public class LearnArrayList {
 public static void main(String[] args) {
              //Creating String ArrayList of initial capacity of 3
  ArrayList<String> arrString = new ArrayList<String>(2);
  //add 4 elements
  System.out.println("Original ArrayList="+arrString);
  //Shuffle Arraylist
  System.out.println("Arraylist after shuffle="+arrString);
  //Sort Arraylist
  System.out.println("Sorted Arraylist"+arrString);
  //Creating an Array from ArrayList
  String[] arrLearn = new String[arrString.size()];
  //Using toarray method
  System.out.println("Newly Created Array=");
  for(int iCnt =0;iCnt<arrLearn.length;iCnt++)

Arraylist after shuffle=[ANGULAR, HTML, CSS, JAVASCRIPT]
Newly Created Array=

Creating Pivot chart for ALM reporting.

How we created our automation progress  report from ALM to Email in 30 minutes?

We need to showcase our management regarding the  progress in Automation.So rather than giving them quantitative data we thought of sharing it in more presentable manner using Pivot charts.

Hope it help our fellow automation friends in creating easy and rapid reports.
Please feel free to share Your experience as comments, as we always believe sharing is caring.

Do follow us for more updates FB,LinkedIn,G+

Download dummy Excel

Step1:- Getting Data from ALM(Application life cycle management),

Note:- It can vary depending on the management tool which is used in the organization but still the approach would be same.
A)Testing -> Test Plan -> Select the Test Folder -> Live Analysis Tab -> Click on 'Add Graph'

Opening Live Analysis view in ALM

B)Select 'Summary Graph' -> Click Next

Summary Graph creation from ALM

C) Select any value for X-axis field -> Click Finish

Selecting X-axis Field in ALM summary graphs

D)Graphical view would be generated -> Click on the bar graph tower

Live Analysis graph in ALM

E)Drill down Results window opens

Drill down results ALM

This is what we were waiting for, we can change what all the columns we need in our report.Further we would export the report in Excel format.

Select columns in Drill down results
Selecting columns in Drill down results view

Export Excel from ALM
Exporting excel from Drill down results

Step2:-Creating Pivot Chart
A)We have our required data in Excel,we can edit to make any required changes like headers or any other modification.
B)Insert -> Pivot Chart

Opening Pivot Chart in Excel

C)Select the Table/Range for Pivot Chart -> Click Ok

Create Pivot Table, range selection Excel

D)Select from "Pivot Chart" Fields, the columns that we need to displayed in Pivotchart report
Pivot chart in Excel

Check the two variations of graph when we changed the data under Axis and Values.

Selecting Pivotchart fields in Excel
Pivot chart view-1

Pivot Chart view-2

Step3 :- Playing with the design of the Pivot chart
One's our chart is ready we can change the color or display design (Like pie chart) to make it look more impressive and easy to comprehend

Just select chart -> click on brush

Changing color in pivot chart

Changing chart styles in Pivot chart

We can also change the shape of graph, INsert -> Charts -> Select the chart option as suitable(Do select the chart below to check the live effect)

Selecting different chart styles in pivot charts Excel

ReRun ALM test
Log BUG in ALM using OTA
Learn Selenium

How to Select random value from a DropDownList using Selenium or UFT

Requirement:- We need to select random value from a given dropdownlist, to test the functionality how our AUT would behave under varying selection of options.
Application Link:
DropDownlist for random selection Selenium
DropDownlist + HTML code

1.We would take the count of existing options in the weblist/dropdownlist .
2.Take a random value between 0(starting index of the dropdownlist, we can avoid in our case as we have --Select-- at 0 index) and maximum value -1(total available options in the list)
3.Select the value based on the random value

Same logic would work whether we are using Selenium or UFT as our testing tool.

1.How to take count of items:-
a.We can use Findelements method to return a list of items and further we would use getSize method of list to fetch the count value.
//Creating the List object
List <WebElement> weblist = driver.findElements(By.xpath(".//*[@id='drpdwnTopics']/option"));
//Taking the count of items
int iCnt = weblist.size();

b.We can use the Select Class and implement its getOptions method to get the count.
Select objSel = new Select(driver.findElement(By.xpath(".//*[@id='drpdwnTopics']")));
List <WebElement> weblist = objSel.getOptions();
//Taking the count of items
int iCnt = weblist.size();

2.How to generate random number, we would implement "Random" class and use its nextInt method to output the random number between the given range.
Note:- nextInt, method would generate number from 0 to upperlimit-1, example nextInt(10), would generate numbers between 0 and 9.

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.*;

public class RandomSelectionDrpDwnList {
 WebDriver driver;
 public void launch()
  driver = new FirefoxDriver();
  driver.manage().timeouts().implicitlyWait(20000, TimeUnit.MILLISECONDS); 
 public void selectRandom()
 //Object of the Dropdownlist
 WebElement drpDwnList = driver.findElement(By.xpath(".//*[@id='drpdwnTopics']"));
 //Using FindElements to create a List object
 //List <WebElement> weblist = driver.findElements(By.xpath(".//*[@id='drpdwnTopics']/option"));
 //Using Select Class to fetch the count
 Select objSel = new Select(drpDwnList);
 List <WebElement> weblist = objSel.getOptions();
 //Taking the count of items
 int iCnt = weblist.size();
 //Using Random class to generate random values
 Random num = new Random();
 int iSelect = num.nextInt(iCnt);
 //Selecting value from DropDownList
 //Selected Value
 public void close()
  //Closing the browser

1.For taking count of items, we would use GetRoProperty in UFT and pass "all items" to fetch the count 
2. Random number is a Utility object , which generates random number between the given range

'Random number is a Utility object , which generates random number between the given range
Dim obj
Set objList = Browser("creationtime:=0").Page("creationtime:=0").webList("html id:=drpdwnTopics")
fnSelectRandom objList

'Function Name:-        fnSelectRandom
'Function Description:- Function to Select Random Value from DropDown
'Input Parameters:-    objList(WebList)
'Output Parameters:-    None
Sub fnSelectRandom(objList)
 Dim iCnt,iRandom,sSelValue
 'Getting the item count of dropdown
 iCnt = objList.GetROProperty("items count")
 'Taking the Random range between 0 and items of Dropdown
 iRandom = RandomNumber(0,iCnt-1)
 'Selecting the value
 objList.Select "#" & iRandom
 'Taking the Selected Random Value
 Print "Selected Value = "&objList.Object.value
End Sub

More Examples
Learning Java 
Learn UFT

Array in Java

What is an Array?
An array is storehouse or we can say collection of similar type of data type.
It is a data structure where we store similar elements. We can store only fixed set of elements in a java array(solution is ArrayList in Java) unlike vbscript where we can have dynamic arrays using Redim keyword.

"Stop being in LOVE with someone who never was and focus on the one who IS". If you Love learning new concepts,Do follow us on FB , G+ , Twitter, or Linkedin

Why Arrays?
It provides code optimization and easy access. Like Instead of declaring individual variables, such as Learn0, Learn1, ...Learn9, we can declare one array variable and use Learn[0], Learn[1], ..., Learn[9] to represent individual variables.

dataType[] arrayName;


dataType arrayName[];


dataType []arrayName;
Memory allocation of Java Array
Memory allocation of an Array

We are declaring an integer array by implementing the above syntax

public class ArrayInJava {
//Array Delcaration in Java
 public static void main(String[] args) {
  int[] Learn;
  int Revise[];
  int []implement;


Assigning a Value :-
We have declared an array, now how can add value into the reserved memory locations of an array like Learn[0] should have 100.
Heap Memory after Array value allocation in Java

dataType[] arrayName = new datatype[arraysize];
arrayName[0] = arrayValue;
arrayName[1] = arrayValue;
arrayName[arraySize-1] = arrayvalue;

dataType[] arrayName = {value1,value2,...value10}

public class ArrayInJava {
//Assigning values to Array in Java
 public static void main(String[] args) {
  int[] Learn = new int[2];
  Learn[0] = 100 ;
  Learn[1] = 200 ;
  int Revise[] = {100,200};
 //Accessing element of an Array
  System.out.println("Approach one Result ="+Learn[0]+";"+Learn[1]);
  System.out.println("Approach Two Result ="+Revise[0]+";"+Revise[1]);

Approach one Result =100;200
Approach Two Result =100;200
Array index always starts with 0 , thus to access the first element we used ArrayName[0].

We have used for loops in working with Arrays.
public class ArrayInJava {
//Working with Arrays Using For Loops
 public static void main(String[] args) {
   //Declaring an Array
  int[] Learn = new int[10];
   //Assinging values to an Array Using For loop
  for (int iCnt = 0 ;iCnt<Learn.length;iCnt++){  
   //Taking the output


Example2:- Passing an  Array to a method and Taking return type also as an Array(This is also an example how we can receive multiple return values from an function)
public class ArrayInJava {
//Passing and Reciveing an Array from a method
 public static void main(String[] args) {
   //Declaring an Array
  int[] Learn = new int[10];
   //Assinging values to an Array Using For loop
  for (int iCnt = 0 ;iCnt<Learn.length;iCnt++){  
  //Calling a method to add 1 to all the array values
  int[] FinalRes = returnArray(Learn);
  //Taking the output of an array
  for (int iCnt = 0 ;iCnt<FinalRes.length;iCnt++){
 public static int[] returnArray(int[] res){
  //Adding 1 to each value of an Array
  for (int iCnt = 0 ;iCnt<res.length;iCnt++){  
   res[iCnt]= res[iCnt]+1;
  //Returning an Array Value
  return res;


Note:- We can use Array.sort(ArrayName); to sort values in a Array.

Multidimensional Arrays:-
Data is stored in the form of rows and columns like a matrix or they way we access the elements of an excel cell A1, B1 ....

dataType[][] arrayName;

int[][] Learn=new int[4][4];//4 row and 4 column

1.What is the difference between char c[] and char[] c in array declaration ?
A. In Java, both are legal and equivalent.First style is preferred declaration and second is  how arrays were declared in C , so it was included for the convenience of programmer moving from c/c++ to Java

2. What is the starting index of an Array in JAVA/vbscript and Why?
A. Starting index is always "0".This convention originated with machine-language programming, where the address of an array element would be computed by adding the index to the address of the beginning of an array. Starting indices at 1 would entail either a waste of space at the beginning of the array or a waste of time to subtract the 1.

3. What happens if we use a negative number(index) to access an array?
A. Whenever we attempt to index an array with an index that is not between zero and the array length minus one, Java will issue an ArrayIndexOutOfBoundsException and terminate the program.

Exploring Data Type & Variables in Java

Java is a strongly typed programming language unlike Vbscript,Perl.In novice terms it means that all the variables in the Java programming language ought to have a particular data type.

Example we cannot use a variable say "xyz" in the code before declaring this like:- String xyz;

What is a Variable?
Variable is the name given to the reserved area allocated in the memory.So we are creating a  variable,we are blocking a  new address space with a unique name.
Variable Type Variable Name;
String Learn;
Where String = Variable Type , Learn = Variable Name.

Variable Type :- it gives what the variable can and cannot hold, as above variable "Learn" can store "String" data.
Variable Name:-Unique name to access the variable.

1.We can declare and assign value to a variable in one go or in two steps,
String Learn = "java";
String Learn; Learn = "java";
String Learn = "java", Revise = "selenium"; 
String Learn,Revise; 
Learn = "java";
Revise = "selenium"
2.Naming conventions for variable Name :-

  • Spaces are not allowed in the Name
  • Characters allowed are A-Z and a-z(small case)
  • Numbers (0-9)
  • Special Characters Only $ and _(underscore) are allowed 
  • Name cannot begin with a number but above special characters are allowed.
  • Reserved keyword in java are not allowed as variable name like new,for,case,continue...
What is a Data type?
Data type specifies the size and the type of values that can be stored in an variable name.

Types :- 
Primitive & Non primitive.

Primitive type is the default data type in Java language and they come with predefined  number of operations.We can not define a new operation for such primitive types.

Following 8  data types are marked as primitive.

Primitive data type Java
Primitive Data Type
public class DataType {
   public static void main (String[] args)
     System.out.println("Size of byte: " + (Byte.SIZE/8) + " byte.");
     System.out.println("Size of char: " + (Character.SIZE) + " bits.");
     System.out.println("Size of short: " + (Short.SIZE) + " bits.");
     System.out.println("Size of int: " + (Integer.SIZE) + " bits.");
     System.out.println("Size of long: " + (Long.SIZE) + " bits.");
     System.out.println("Size of float: " + (Float.SIZE) + " bits.");
     System.out.println("Size of double: " + (Double.SIZE) + " bits.");
     System.out.println("Size of Boolean: -- bits.");

Size of byte: 1 byte.
Size of char: 16 bits.
Size of short: 16 bits.
Size of int: 32 bits.
Size of long: 64 bits.
Size of float: 32 bits.
Size of double: 64 bits.
Size of Boolean: -- bits.

How the range of a Data Type is assigned:-
Like why byte datatype range starts from -128 to 127.
In our above diagram we associated a particular range set with a given data type , say Int is 4 byte(32 bit) but how this is computed.We would go into our school days to comprehend this process.

Computer memory store numbers in the form of binary system(meaning 0 or 1). And our memory is like a grid of cell.Now each cell contains binary data(in the form of 0 or 1 called as bit).

Memory data cell

Our data flow in the form of 8 bits meaning we have 8 places to put our bits , thus incase we make them all 1 in each cell it comes as (1111111 in binary ) which is equivalent to 255 in decimal system.Further to take the minimum we can have all bits have 0 each. So the number from 0 to 255 can fit the 8 bits.
Data Range for a Byte in Java

Out of this 8 bits one bit is reserved for holding the sign of a number(positive or negative) so we are left with 7 bits , thus maximum  7 bits can hold is (1111111 = )127 in decimal system.Similarly for minimum values we have 7 bits of 000000 and 1 bit for sign which comes as(10000000) - 128 in decimal system.
Byte Data Type in JAVA

So our 8 bits can hold numbers ranging from -128 to 127(including 0) or a total of 256 numbers.

Non primitive (Reference type) :- classes(String Class) , arrays.

Primitive v/s Reference type:-
For a variable of a primitive type, the value of the variable is stored in the memory location assigned to the variable. So, if an integer variable is declared as “int days = 100″, then when we look at the memory location of “days”, "100" would be  stored there just as expected.

However, a variable of a class type(Non Primitive) only stores the memory address of where the object is located – not the values inside the object. So, if we have a class called “learn selenium”, when we create an object(say obj) and if check the this object in memory, we will see that it does not store any of the variables that belong to that object in memory.

Instead, the variable “obj” just stores an address of another place in memory.This means that the object named by the variable is stored in some other location in memory and the variable contains only the memory address of where the object is stored. This memory address is called a reference to the object.

Example :- 
str = new String("example of reference"), it would work like :-
1.Evaluate the expression , new String("example of reference")
this expression creates an new object, which creates an reference to an object which decriobes its location in memory.
2.Store the value in the variable (str)
str= The reference to string created

Now whenever the program needs to refer to the object it uses the variable str.And str contains the reference of memory location where string exists.

How to get variable type in Java?
Non Primitive Type:- 
We can directly get it by using getClass() and getSimpleName() methods.
package Java;
public class DataType {
 public static void main(String[] args) {
 //We have a variable
 String Learn = "Selenium";
 //Lets check Class of Variable
 System.out.println("Class = "+ Learn.getClass());
 //Lets check Type of Variable

Primitive Type
We need to create the object of Datatype to use the above methods.
package Java;
public class DataType {
 public static void main(String[] args) {
 //We have a variable
 int noOfDays = 365;
 //Create object
 Object obj = noOfDays;
 //Lets check Class of Variable
 System.out.println("Class = "+ obj.getClass());
 //Lets check Type of Variable
How to find Datatype of Primitive variables
Output of Int DataType

Meaning of Arrays in Java

Key Components of JAVA

JDK, JRE and JVM are core concepts of Java programming language. As a novice in this language we should try to comprehend these concepts to visualize how it works logically.

For more updates do follow us on Facebook,Twitter or Google+

JDK and JRE n Java

Java Development Kit (JDK) consists of tools needed to create the Java programs,like Java libraries, Java compiler(javac.exe), Java debuggers, bundling and deployment tools.It also contains the JRE to run the java programs.We need to install the platform specific JDK like for windows,linux.We did installed the JDK while understanding the prerequisites for Selenium.

In nutshell JDK,is required to create our own java programs and to compile them as bytecode.Further we need JRE only for running the programs.

Javac:- Meaning Java Compiler,which takes programming code(java) as input and produces an executable code(bytecode) as an output.This is further executed by JVM into native code (machine code) as per the platform(windows,linux,mac,solaris)

ByteCode:-It is stored in .class file and cannot be read by standard CPU's and needs to be translated into an instruction language that the underlying execution platform(Windows,linux) can comprehend.

we must have experienced this thing that while trying to run any  java application on browser or in mobile,browser often suggest to download the JRE to run the program.

Thus JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes( like math, lang, awt,swing etc)+runtime libraries. Java code comes in the bundled form of JAR  (Java archive) files(remember we also used selenium JAR files to create test scripts)and we require Java virtual machine JVM to execute it.JRE is again platform dependent like JDK

JAVA virtual machine is the key for converting byte code into machine specific code.Moreover we have multifarious JVM as per the operating system like for Windows, Linux or Mac but one JAR(byteCode) can run on all these operating systems. 

Java Virtual machine is at heart of Java programming language and provide several features  to Java programmer including Memory Management and Garbage Collection, Security and other system level services.

JVM is the backbone of the "write once and run everywhere" principle in JAVA

1)  Both JDK and JRE come as installer while JVM are bundled with them.
2)  JRE only contain environment to execute java program but doesn’t contain other tool for compiling java program like JDK. In short JDK is for development purpose whereas JRE is for running of java programs.If we only need to run the Java code then JRE is recommended option but for full fledge development package JDK is preferred option.
3) JVM comes along with both JDK and JRE , it is like heart of java programming language and provides platform independence.

1)JIT (Just in Time) or dynamic compilation is part of JVM that optimizes bytecode to machine specific language compilation.
What happens is:- An JVM interpreter generates and executes the machine code instructions on the fly for each instruction, regardless of whether it has previously been executed.Now JIT caches the instructions that have been previously been interpreted to machine code, and reuses those native machine code instruction thus saving time and resources by not having to re-interpret statements that have already been interpreted by compiling similar bytecodes at same time, hence reducing overall time taken for compilation of bytecode to machine specific language.

2)Eclipse IDE comes with its own java compiler , it is different from javac, like it allows to run the code that did not actually properly compile and incase the error code block is never ran, our program would run fine.Further it comes with incremental feature, which allows our code to be pre-compiled as soon as we are finish typing.

Introduction to JAVA
DataType in Java