How to take a screenshot using Selenium?

Automation testing is not complete without error reporting and screenshots reporting the error will help users debug the issue faster and more efficiently. The interface TakesScreenshot is used to implement this. It is typecasted on to driver. A menthod called getScreenshotAs which takes an input as a file is then used and is stored in a File .Finally this file is copied to the destination file of the user’s choice

        //Sample code to take a Screenshot
        TakesScreenshot ts = (TakesScreenshot) driver;
        File scrnShot = ts.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrnShot, new File("/c:/myscreenshot.jpg")); 
        // END Screenshot
//This can be alternatively done in a combined way as follows:
File Scrnshot = (TakesScreenshot)driver.getScreenshotAs(OutputType.File)
FileUtils.copyFile(scrnShot,new File("/c:/myscreenshot.jpg"));


Selenium Commands – Multiple Window handling

One of the common commands that is used in automation is handling multiple windows. Often you have a website where when you click on a tab or link brings up another window and then from that window you can open another pop up window .To handle such a situation , there are two methods in Selenium getWindowHandle and getWindowHandles . They will return window id of the current window in case of former and a list of window ids in case of latter.

As show in the code below, the “main_win” will get the window id of the first window. The “otherwins” stores the window ids in a Set as they need to be unique. Next use an iterator on the windowids so you can manipulate each of the windowids by comparing if they are equal to the main window and then switching to the desired window using the driver.switchTo().window(child_win) command.You can get title of the window and do many such operations. To fall back to the original window , the command driver.switchTo().defaultContent() can be used.

        // Sample code Using getWIndowHandle and getWindowHandles

        String main_win= driver.getWindowHandle();
        Set <String> otherwins = driver.getWindowHandles();
       //Use an iterator on the window handles obtained as below.
        Iterator <String> it = otherwins.iterator();
        while (it.hasNext()) {
            String child_win=;
            if (! main_win.contentEquals(child_win)) {
                System.out.println("the title of the window" + 


Selenium Commands – Automate Dropdown and checkboxes

Automating dropdown boxes using Selenium , we use Select class and after you create an object of the class you can use SelectbyVisibleText, SelectbyValue or SelectbyTagName. When you use Rightclick to inspect on the element you will be able to find a list of text and value used in the dropdown .The tagname can also be obtained from here .

A sample code for automating the dropdown and selecting a value by visible text is below:

WebElement dropdown = driver.findElement(By.cssSelector("mypath"));
Select s = new Select(dropdown);

//Finding a list by tagname options and finding attribute
    List <WebElement> lvalues = driver.findElements(By.tagName("options"));
    for (int i=0; i<=lvalues.size(); i++) {
    System.out.println("The list is"+   lvalues.get(i).getAttribute("countries"));


//CHECKBOX TEST to select all checkboxes

        List <WebElement> chkBox = driver.findElements(By.className("testclass"));
        for (int c=0; c<=chkBox.size(); c++) {
//or you can write as follows
       /*   for (WebElement cbox:chkBox) {
        } */


Selenium Commands – Mouse and Keyboard Related

Sample Selenium code for mouse and keyboard gestures related actions. Often automation requires navigation to a page and using mouse gestures and keyboard actions to move to a main menu and then to the menu item and click on it . This can be achieved by Actions class in Selenium. Create an object of actions class and pass the driver reference .Then use it along with the methods like movetoElement, sendkeys, KeyDown etc to manipulate the keyboard actions and gestures.

   // Sample code 
	WebDriver driver = new ChromeDriver();
	driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
	driver.navigate().forward(); //just for learning
	String mytitle = driver.getTitle();
	System.out.println("the title of the page is " +mytitle);

//To find xpath of a menu and click on the sub-menu item, first find the xpath then use Actions class  and move to Element and use perform method.

    WebElement mymenu = driver.findElement(By.xpath("//*myxpath"));
    Actions action = new Actions(driver);

//Here finding the xpath of the menuitem under menu and using click method
    WebElement menuitem1 = driver.findElement(By.linkText("Click here"));

//Using Keyboard keys to enter and combination of keys using Keys.chord for copy paste action using ctl a , ctrl c and ctrl v

    WebElement myitem1 = driver.findElement(By.cssSelector("csscode"));
    Actions act = new Actions(driver);
    act.sendKeys(Keys.chord(Keys.CONTROL+ "c")).perform();
    WebElement myitem2 = driver.findElement(By.cssSelector("csscode2"));

 // Using Keyboard keys for scrolling page down and page up
//The above scrolling can also be done using JavaScript Executor
    JavascriptExecutor js = (JavascriptExecutor)driver;
    js.executeScript("windows.scrollBy(0,250)", "");
    js.executeScript("windows.scrollBy(250,0)", "");

How to set up Selenium environment ?

Setting up Selenium testing environment with Java.

We need to download the following :

  1. Selenium standalone server ( ->Latest stable version  selenium-server-standalone-3.141.59 jar file
  2. Selenium Client & Web driver language bindings ( Scroll down to find this selenium-java-3.141.59 zipped file )
  3. Google Chrome Driver (Under Third party drivers and browsers Scroll down to find Chrome and this chromedriver_win32 zipped file )

We also need to install

  1. JDK 8.0 (create JAVA_HOME and set PATH to bin folder of JRE location) Note: Java 12 and the version of Selenium had issues so I used Java 8.
  2. Eclipse IDE 2019-06 (4.12.0) (

Click on Project -> Properties to bring the properties window

Navigate to Java Build Path ->Libraries ->set execution environment :

From Eclipse Go to File ->New -> Java Project ->Create a new project -> -> Right Click ->Build Path -> Configure Build Path -> Go to Libraries tab ->Add External Jars -> Point to the selenium standalone server jar

Write a test code to see if the setup works .


Selenium is a suite of software tools to automate web browsers and can be used to automate testing of web applications .It is opensource and mainly used for functional and regression testing .Selenium supports the following:

  • Programming Languages: Java, Pythin,C#,PHP,Ruby,Perl,JavaScript.
  • Operating System: Windows,Mac,Linux,ios,Andriod
  • Browsers: IE,Firefox,Chrome,Safari,Opera
  • has all the documentation and downloads


  1. open source software
  2. supports many programming languages and OS
  3. supports many browsers
  4. supports frameworks TestNG,JUnit and Nunit


  1. supports only web applications
  2. only user communities available
  3. difficult to set up and use
  4. no reporting facility
  5. limited support for image based testing

Selenium suite of tools consists of : IDE, RC, Web Driver and Grid

  • Selenium 1: IDE+RC+Grid
  • Selenium 2 : IDE+ RC *(deprecated) + Web Driver + Grid
  • Selenium 3: IDE+RC*(deprecated) + Web Driver+ Grid

Selenium IDE –

  • Firefox plugin is used to create and execute testcases
  • records and plays back interactions which user had with web browsers
  • export the program code in different languages.

To get IDE go to ,download it and add it to firefox .Click on selenium IDE.Click on any website say amazon.Open IDE window , you will see selenese commands under command and target .Play using the play button.YOu do a File->save testcase and Export test case as Java/TESTNG/Webdriver.This creates java files@TESTNG options .

This is primarily used to create prototype and sample not full fledged testing .It can be used to get syntax , loops and data driven testing cannot be done with this . The disadvantages are it supports only mozilla, not suitable for dynamic web applications for ex. password field where passwords cannot be changed,you can use xpath , no data driven testing, no support for programming languages and no centralized maintenance of elements and objects.

Selenium Remote Control –

  • This is used to write web application tests in Programming languages.
  • It interacts with the browsers with help of Selenium RC server .
  • RC server communicates using simple HTTP GET/POST requests
  • Every communication with RC server is time consuming and so ends up being slow
  • Deprecated from Selenium 3

RC vs WebDriver – Jason Huggins created a java script program that would automatically control browsers actions called JavaScriptRunner and made it open source (called selenium core)

Same origin policy issue – This prohibits JS code from accessing elements from a domain that is different from where it was launched .(For eg. If you launched ,you will not be allowed to access elements in

This is why prior to Selenium RC testers needed to install local copies of both Selenium Core (JS Program) and web server containing apps so they belong to same domain.

Paul Hammart created a server that will act as an HTTP proxy to trick browser into believing selenium core and web applications being tested come from same domain .This came to be known as Selenium Remote control or selenium 1 .It creates a fictional url to believe core and url are under the same domain.

However this was a slower system as you first start servers, http proxy gets injected, instruction script goes into selenium core sitting in your browser.Selenium core will send instructions to your browser.No direct communication between script and browser or web application.Start Server->Instruction script send to->selenium core sends to->browser

Selenium Web Driver –

  • Most widely used and popular one .It has a programming interface to create and execute test cases.
  • Testcases are created and executed using Elements, Object locators and Web Driver methods .
  • It has a programming interface not IDE
  • It’s fast as it interacts with browsers directly. No server or core

All pages have elements/objects .Once you get element get a click.To automate you need to find elements .Different locator techniques to find web elements.We have 8 element locator techniques .Each browser has its own driver on which application runs.Selenium web driver makes direct calls to browser.

The advantages are the support for multiple programming languages, browsers and OS and it is fast.Selenium 1 limitations like upload,download,pop-up and dialogs are overcome.The disadvantages are no reports are generated and no centralized maintenance of objects and elements.

Selenium Grid

  • This helps run multiple test scripts at same time on multiple machines
  • Parallel execution by Hub-node architecture.
  • Hub controls test scripts or browsers
  • Using jar files, supports RC based as well as webdriver test.

Java Program to convert a hexadecimal number to binary and print in a 2d array

This program asks for a hexadecimal input and converts into binary number .The code also uses enhanced for loop to print the 2d array .In this example we have array[2][4] that is 2 rows and 4 columns .It fills the row [0] first then row[1] with the elements in the array[a,b] .

package Main;
import java.util.Scanner;
public class hexatoBinary {
public static void main(String[] args) {
			for(int i = 0; i<5; i++) {
				System.out.println("Please enter your hexadecimal number.");
				Scanner kb = new Scanner(;
				String numb = kb.nextLine();
				String numb1 = Integer.toBinaryString(Integer.parseInt(numb.substring(0,1), 16));
				String numb2 = Integer.toBinaryString(Integer.parseInt(numb.substring(1,2), 16));
				System.out.println("number 1 is " +numb1);
				System.out.println("number 2 is " +numb2);
				numb1= ("0000"+numb1).substring(numb1.length());
				numb2= ("0000"+numb2).substring(numb2.length());
				System.out.println("number 1 now is " +numb1);
				System.out.println("number 2 now is " +numb2);
    char[][]arr1 = new char [2][4];
    for(int a=0; a<2; a++) {
    	for(int b = 0; b< arr1[a].length; b++) {
    		if(a==0) {    // first row filling
    			arr1 [a][b]= numb1.charAt(b);
    		if(a==1)    // second row filling
    			arr1 [a][b]= numb2.charAt(b);

    for(char[] p: arr1) { //enhanced for loop for multi dimensional array
    	for(char b: p) {
    		System.out.print(b+" ");
    	System.out.println(" ");



8.Java OO concepts – Encapsulation,Inheritance,Abstraction and Polymorphism.

What is Encapsulation ?

Variables in a class can be set to private and thus hidden from outside world or other classes. They can be accessed by using setter or getter methods that are public or protected to modify . see example below for better understanding

class NewHire{

    private float salary; // --These private variables are hidden from outside classes --,getter and setter methods below are used for other classes  to access them and this --is a good example of encapsulation and how data is hidden .
    private float sickdays;
    private float holidays;

    public float getsalary() {
        return salary;
    public void setsalary(float salary) {
        this.salary = salary;
    public float getsickdays() {
        return sickdays;
    public void setsickdays(float sickdays) {
        this.sickdays = sickdays;
    public float getholidays() {
        return holidays;
    public void setholidays(float holidays) {
        this.holidays = holidays;
public class EncapsulationTest {
    public static void main(String[] args) {
        NewHire h1 = new NewHire();

        // using setters of NewHire
        // using getters of NewHire
        System.out.println("Person has "+h1.getsalary()+" salary and hass "+h1.getsickdays()+"  sickdays and number of  holidays are "+h1.getholidays());

What is Inheritance ?

The objects of a class namely methods and variables can be inherited by another class as it’s own simply by using the keyword extends . A child class or sub class, can only inherit from one parent class also called super class . A parent class can however have multiple sub classes. All methods except those that are private are inherited by the child class. This can also be best explained with an example below.

/*Super class CARS is a parent of sub class ElectricCar below*/

public class Cars {
    public int price;
    public void testSpeed(){
        System.out.println("Checking Speed...");
    public void getColor(){
        System.out.println("Getting color...");
    // private method  not visible to other classes
    private void securecheck(){
        System.out.println("This is confidential to Cars");

/** This class ElectricCar is a subclass and inherits from  Cars */

public class ElectricCar extends Cars {
    public String name;
    public static void main(String[] args) {

        ElectricCar venzaE = new ElectricCar();
        = "Tes VenzaE"; // var of ElectricCar ie subclass
        venzaE.price = 90500; // var of Cars ie Super Class
        venzaE.playMusic(); // method see below of ElectricCar ie SubClass
        venzaE.testSpeed(); // methods of Cars ie Super Class
        venzaE.getColor();; // methods of Cars ie Super Class
    	public void playMusic(){
        	System.out.println("Playing Music Channel ");

What is Abstraction ?

Data Abstraction is the property by which complexities and non essential units are not displayed to user .It only shows the required or essential details . One may wonder the difference between data encapsulation and abstraction .A simplest way to explain would be encapsulation is “data hiding” where as data abstraction is “implementation hiding”. Encapsulation groups data and methods that act upon the data, data abstraction exposes the interface to the user and hides the details of implementation.

So what is an interface ? We saw earlier how inheritance allows a subclass to inherit from a super class .Java does not allow to inherit from more than one class. So to add additional functionality, we create what is called an interface. Interfaces are empty classes. They provide all of the methods you must use, but none of the code.Methods declared in an interface are by default abstract (only method signature, no body).  They usually have an adjective name like “Drivable” below.

Example Interface Drivable

public interface Drivable {
double PI = 3.14159265; //fields in interface are final and cant change
int getWheels(); // All methods in an interface are public and abstract by default. An abstract method must be defined with implementation detail by any class  that uses the interface.
void setWheels(int numWheels); // Methods are by default abstract ;It can not be final and abstract ; final means the method can't be changed and  abstract means it must be changed hence cant be both!
double getSpeed();
void setSpeed(double speed);

Example Class Vehicle using the Interface Drivable and abstract class Crashable

/* For a class to use an interface we use  the "implements" keyword. This class should have the methods implemented for each method defined in Drivable interface .You can have more than one interface.Now if you have another class say Crashable which is an abstract class and want to make it part of the abstract class use the "extends" keyword */
public class Vehicle extends Crashable implements Drivable {
	int numOfWheels = 2;
	double theSpeed = 0;
	int carStrength = 0;
/* All methods must be as visible as those in the  interface. If they are public in the interface they must be public in the subclass */
	public int getWheels(){
		return this.numOfWheels;
	public void setWheels(int numWheels){
		this.numOfWheels = numWheels;
	public double getSpeed(){
		return this.theSpeed;
	public void setSpeed(double speed){
		this.theSpeed = speed;
	public Vehicle(int wheels, double speed){
		this.numOfWheels = wheels;
		this.theSpeed = speed;
	public void setCarStrength(int carStrength){
		this.carStrength = carStrength;
	public int getCarStrength(){
		return this.carStrength;

Example Abstract class Crashable used in class Vehicle with extends

/* If you want to create a class in which every method doesn't have to be implemented use abstract classes. Create an abstract class with the abstract keyword */

public abstract class Crashable{
	boolean carDrivable = true;
	public void youCrashed(){
		this.carDrivable = false;
	public abstract void setCarStrength(int carStrength);
	public abstract int getCarStrength();

Example Main program calling all the above

public class LearnOOPInterfaceAbs {
	public static void main(String[] args){
		Vehicle car = new Vehicle(4, 100.0);
		// Using methods from the interface Drivable
		System.out.println("Cars Max Speed: "+car.getSpeed());
		System.out.println("Cars Number of Wheels: "+car.getWheels());
		// Using methods from abstract method Crashable
		System.out.println("Car Strength: "+car.getCarStrength());


  • Interface : Drivable – defines methods and fields to be used no details
  • Class: Vehicle – defines all methods ,fields with implementation
  • Abstract Class : Crashable – defines methods not required to have details of implementation
  • Main Program : Calls the Vehicle class by creating a new object and uses methods from Drivable interface and abstract methods from Crashable
  • As we see the interface and abstract class hides the implementation details and only has what is necessary this is data abstraction.
  • We can’t create instance(interface can’t be instantiated) of interface but we can make reference of it that refers to the Object of its implementing class.
  • From Java 9 onwards, interfaces can contain static,private and static private methods but they cannot be inherited.
  • Interfaces are used to implement abstraction. You may wonder why use interfaces when we have abstract classes? The reason is, abstract classes may contain non-final variables, whereas variables in interface are final, public and static.

What is Polymorphism ?

“Poly” means many and “morph” means forms .Basically it means to take on many forms. With inheritance and many multiple methods ,this can be really useful .There are two types of polymorphism static (or compile-time) and dynamic (or runtime) .

  • In static polymorphism, methods can have the same name but different signatures . For eg. one of the methods may have 2 parameters and the other 3 OR one method may accept integers and other a double OR one method may accept strings and integers and other integers and strings, i.e they are in a different order(this is not usually used).It allows compiler to know which method has to be called and binds it to method call.
  • In dynamic polymorphism ,the JVM determines the method to be executed at runtime .As we have already seen in inheritance , a sub class can override a method of its super class and establish its own behavior. The method names of both the super class and sub class may be same and even with the same parameters but provide different implementation.


// Animal is as a Super class example
public class Animal {
	private String name = "Animal";
	public String favFood = "Food";
	protected final void changeName(String newName){ // protected so other methods can call,final means it cant be changed by other classses = newName; //this is reference to object being created
	protected final String getName(){
	public void eatStuff(){
		System.out.println("My fav food " + favFood);}
	public void walkAround(){
		System.out.println( + " walks around");}
	public Animal(){}
	public Animal(String name, String favFood){
		this.favFood = favFood;


// Cat is a Subclass of Animal .You create subclasses with the extends keyword and Cat has all the Methods and Fields that Animal defined because Cat inherits all the methods and fields defined in Animal

public class Cat extends Animal{
public String favToy = "Yarn"; //  adding new fields to the subclass
public void playWith(){ // You can add new methods
System.out.println("Yeah " + favToy);}

public void walkAround(){ // METHOD OVERRIDE EXAMPLE ----
    System.out.println(this.getName() + " stalks around and then sleeps"); // this refers to a specific object created of type Cat }

public String getToy(){ return this.favToy;
public Cat(){ }
public Cat(String name, String favFood, String favToy){
     super(name, favFood); // super calls the constructor for the super class Animal
     this.favToy = favToy; // We set the favToy value in Cat because it doesn't 
    exist in the Animal class
} }


public class LearnPolyMorphism{
public static void main(String[] args){ //Create Animal Object
		Animal genericAnimal = new Animal();

		Cat morris = new Cat("Morris", "Tuna", "Rubber Mouse"); //create CAT class
		// Print out the name, favFood and favToy
		// You can also create classes based on the super class
		Animal tabby = new Cat("Tabby", "Salmon", "Ball");
		// You pass objects like any other field
	public static void acceptAnimal(Animal randAnimal){
		// Gets the name and favFood for the Animal passed
		// This is Polymorphism , interpreter automatically figures out what type of Animal it's dealing with and checks to make sure if methods were overwritten that they are called  instead

		// The interpreter won't find anything that doesn't originally exist in the Animal class however for example  System.out.println(randAnimal.favToy); Throws an ERROR
		// If you want access to fields or methods only found in the Cat class you have to cast the object to that specific class first

		Cat tempCat = (Cat) randAnimal;
		// You could also cast the object directly like this

		System.out.println(((Cat) randAnimal).favToy);
		// You can use instanceof to check what type of object you have. This results in a positive for Animal and for Cat

		if (randAnimal instanceof Cat)
			System.out.println(randAnimal.getName() + " is a Cat");

7. Arrays

An array is a collection of variables of the same type . Each element has an index and can hold a single item.They can be primitives or object references.The length of array is fixed when created.Arrays are objects.You can think of arrays like a box with a number of boxes.

Arrays can be declared in many ways:

    int[] myArray;  // dataType[] arrayName
    int[] myArray = new int[10]; //  dataType[] arrayName = new dataType[sizeOfArray];

Array values can be added in many ways:

    myArray = new int[20]; //declare and assign
    randomArray[1] = 2;
    String[] myArray = {"Just", "Random", "Words"}; //Create the array and assign values
     for(int i = 0; i < myArray.length; i++) // You can add using for loop start
    {  numberArray[i] = i; }

Multidimensional arrays are also supported by Java .Multi dimensional arrays can be explained as array of arrays .Each element in an array point to another array.

Multidimensional arrays can be of type Matrix or Jagged .As seen the matrix array will have the row and column defined whereas the jagged will have the column empty as it can be of variable type

6. Flow Control Types & Operators

Data flow control can be of four types

  • Sequential – Follows a simple sequential path,executing one statement after another .
  • Selection – This follows conditional execution of statement or block of code .For eg If else statement or switch statement
  • Iteration – Here one statement or block of code is executed repeatedly or ended depending on the expression evaluation to true or false Eg. while,do ..while, for loop
  • Transfer – Here execution jumps to various points .This is considered poor programming style as logic is difficult to follow and maintaining code is not easy.

Sample If else statement

if (priceCheck < 100)
else if (priceCheck > 100)

Sample switch statement

 char myGrade = 'A';
/* The switch statement checks the value of myGrade to the case and executes the code between {} if satisfied and then break ends the switch statement default code is executed if no matches are found . The break or default statements are not mandatory. The expression must be an int, short, byte, or char */
    switch (myGrade)
    case 'A':
        System.out.println("Very Good");
        break; // Switch statement ends
    case 'B':
        System.out.println("Good, try to get an A next time");
    case 'C':
        System.out.println("OK, you have more potential");
    case 'D':
        System.out.println("Work hard");
        System.out.println("Sorry, You failed");

Sample while loop

int i = 1; // create a loop iterator before the loop begins

while(i < 20) { // Use continue to skip over printing 3 
if(i == 3) {
 i++; // Just print odd numbers
 if((i%2) == 0) { i++; } 
 if(i > 10) { break; // when i is greater than 10 jump out of the loop and break out it prematurely} }

Sample do while loop

 // It's  used when you know the code between {} will execute at least once.  loop iterator is created before expression is evaluated

int g = 1;
    } while (g <= 25); // Counts from 1 to 25



Sample For loop

// for( declare iterator; conditional statement; change iterator value)

for (int l=10; l >= 1; l--)

Relational Operators:

Java has 6 relational operators

  • > : Greater Than
  • < : Less Than
  • == : Equal To
  • != : Not Equal To
  • >= : Greater Than Or Equal To
  • <= : Less Than Or Equal To

Logical operators

  • ! : Converts the boolean value to its right to its opposite form ie. true to false
  • & : Returns true if boolean value on the right and left are both true (Always evaluates both boolean values)
  • && : Returns true if boolean value on the right and left are both true (Stops evaluating after first false)
  • | : Returns true if either boolean value on the right or left are true (Always evaluates both boolean values)
  • || : Returns true if either boolean value on the right or left are true (Stops evaluating after first true)
  • ^ : Returns true if there is 1 true and 1 false boolean value on the right or left