How to Handle Alerts in Selenium WebDriver

The Hacks of The Day

In this tutorial, we will let you know about different types of alert appeared in web applications and how to handle these Alerts in Selenium WebDriver. We will also figure out how do we accept and reject the alert depending upon the alert types. Alert is a small pop up window that comes up on the screen. There are numerous user activities that can bring about an alert on-screen. For e.g. user clicked on a button that displayed a message, The HTML page asked you for some extra information. So in this article, we will learn how to Handle Alerts, JavaScript Alerts, and PopUp Boxes in Selenium WebDriver.

What is Alert?

An alert is a small dialog box that displays on-screen. It gives some kind of information to the user or asks for permission to perform a certain kind of operation. It can be also used for warning purposes. Alerts are different from regular windows. The major difference is that alerts are blocking in nature, they will not allow any action on the underlying webpage if they are present.

How to handle Alert in Selenium WebDriver

Selenium WebDriver provides the following methods to interact with the Alerts depending on the Alert types.

1. void dismiss(): It is used to cancel the alert
driver.switchTo().alert().dismiss();

2. void accept(): It is used to click on ok button of the alert
driver.switchTo().alert().accept();

3. String getText(): It captures the alert message text
driver.switchTo().alert().getText();

4. void sendKeys(String stringToSend): It sends some data to alert
driver.switchTo().alert().sendKeys("Text");

1. Simple alert

Simple alerts have just the ok button on them, they give some information to users. Following is the practice example of a simple alert in Selenium Webdriver.

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SimpleAlertBox {
 public static void main(String[] args) {
  System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
  WebDriver driver = new ChromeDriver();
  // Launch the URL
  driver.get("https://www.testandquiz.com/selenium/testing.html");
  driver.manage().window().maximize();
  driver.findElement(By.xpath("//button[text()='Generate Alert Box']")).click();
  // First Alert class will shift the focus to the alert box
  Alert alert = driver.switchTo().alert();
  // Accept() method will accept the alert box
  alert.accept();
  // Close the browser
  driver.close();
 }
}

2. Confirmation Alert

Confirmation Alert comes with two options (Ok/Cancel), you can accept it or dismiss it. It requires user confirmation to perform some task. Users can accept it or cancel it. Here is a code to dismiss the confirmation alert.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ConfirmationAlert {
 public static void main(String[] args) {
  System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
  WebDriver driver = new ChromeDriver();
  // Launch the URL
  driver.get("https://www.testandquiz.com/selenium/testing.html");
  driver.manage().window().maximize();
  driver.findElement(By.xpath("//button[text()='Generate Confirm Box']")).click();
  Alert confirmationAlert = driver.switchTo().alert();
  confirmationAlert.dismiss();
  // Close the browser
  driver.close();
 }
}

3. Prompt Alert

In the prompt alert, you can enter some text by using sendkeys method. These alerts are used when some information is required from the user side. Here is the code example for the prompt alert.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PromptAlert {
 public static void main(String[] args) {
  System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
  WebDriver driver = new ChromeDriver();
  // Launch the URL
  driver.get("https://www.khawarautomationlabs.com/2020/04/alerts-in-selenium-webdriver-in-this.html");
  driver.manage().window().maximize();
  driver.findElement(By.xpath("//button[text() = 'Click on me']")).click();
  Alert promptAlert = driver.switchTo().alert();
  String alertText = promptAlert.getText();
  System.out.println("Alert text is: " + alertText);
  promptAlert.sendKeys("Prompt Alert");
  promptAlert.accept();
 }
}
Prompt popup Sample

Prompt Box Example

Prompt Box Click the button to open the prompt box.

How to Click on Image in Selenium Webdriver

The Hacks of The Day

In this tutorial, we will let you know how to click on an image in Selenium WebDriver. When a user clicks on an image it redirects the user to a different window or page. As shown in the below image, when the user clicks on the "Facebook" logo, it redirects to the homepage.


We can't find image elements by By.linkText() and By.partialLinkText() methods because image links basically have no link texts at all. In this case, we can use CssSelector or XPath.

In the below example, we will access the "Facebook" logo on the upper left portion of Facebook's Password Recovery page.

Scenario:
  1. Go to this URL https://www.facebook.com/login/identify?ctx=recover
  2. Click on Facebook logo
  3. The home page will show
1) Click on image By using XPath
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ClickOnImageByXpath {
 public static void main(String[] args) {
  String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
  System.setProperty("webdriver.gecko.geckodriver",
  "/home/khawer/eclipse-workspace/TrainingVideos/geckodriver");
  FirefoxDriver driver = new FirefoxDriver();
  driver.get(baseUrl);
  driver.findElement(By.xpath("//a[@href  = 'https://web.facebook.com/']")).click();
  if (driver.getTitle().equals("Facebook – log in or sign up")) {
   System.out.println("We are at Facebook's homepage");
  } else {
   System.out.println("We are not at Facebook's homepage");
}
2) Click on image By using CssSelector
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ClickOnImageByCssSelector {
 public static void main(String[] args) {
  String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
  System.setProperty("webdriver.gecko.geckodriver",
  "/home/khawer/eclipse-workspace/TrainingVideos/geckodriver");
  FirefoxDriver driver = new FirefoxDriver();
  driver.get(baseUrl);
  driver.findElement(By.cssSelector("a[title=\"Go to Facebook home\"]")).click();
  if (driver.getTitle().equals("Facebook – log in or sign up")) {
   System.out.println("We are at Facebook's homepage");
  } else {
   System.out.println("We are not at Facebook's homepage");
  }
 }
}

How to access forms in Selenium with Java

The Hacks of The Day

Have you noticed the ubiquity of web forms while surfing the internet? Almost every website or web-application you visit has an interface in the form of web-forms to collect the necessary information about yourself. A webform comprises web elements such as checkbox, radio button, password, drop down to collect user data.

If you are going to perform automated browser testing for your website or web-application then you simply can’t afford to drop-out the forms from your test automation scripts. In the case of test automation, Selenium has an API (Application Programming Interface) that helps to find these web elements and take subsequent actions on them like selecting a value or entering some text.

This article will help you to understand how you can access web forms in Selenium to automate the web application. I will be using the JUnit Framework with some annotations to execute our Selenium automation testing later in this article.

To begin our learning with, we’ll first understand what a WebElement is, how can it be accessed in Selenium Automation, and then go about seeing the basic form elements like the input boxes, buttons, the actions that can be performed on these forms and finally writing a script to handle a form and run it on various browsers. If you are already aware of the basics then feel free to skip through the sections according to yourself:

What Is A WebElement?

In simple words, anything present on a webpage constitutes a WebElement. Examples can be a text box, a radio button, etc. Selenium Webdriver provides an interface that is called the WebElement which is responsible for all the possible actions that take place on the web page. To locate the web elements, the Selenium web driver provides the two methods which are given below

  1. findElement()
  2. findElements().

findElement(): It locates the single web element. After finding the element is found it is returned as a WebElement object. Let us now see the syntax of findElement(), but before we start using the WebElement object in our test script we need to make note of one very important point.

We need to import the following packages to start creating objects of the WebElements:

import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebElement;

Syntax for findElement():
WebElement ele = driver.findElement(By.id("id");

WebElement ele = driver.findElement(By.xpath("xpath");
findElements(): It returns a list of WebElements that corresponds to the locator defined in the method.

The syntax for findElements() is as shown below:
List<WebElement> ele = driver.findElements(By.xpath("xpath");

Now that we are thorough with the understanding of the WebElement interface, along with the difference between findElement() & findElements() method in Selenium automation testing. It is time to deep dive into these web elements. We will now list down all the web fields that may be involved in your website or web application form. Now we will learn how to access web forms in Selenium WebDriver.

How To Locate Web Elements

Now we know that what different types of web elements we can come across in our application, We need to identify these web elements through our Selenium automation testing scripts and to do so first we need to find the locators. Locators are the parameters given to the findElement() or findElements() methods which help to retrieve the web element by using its properties like the ID, Name, Class, etc. In general, we have 8 locators in Selenium that are widely used:
  • ID
  • Name
  • Tag Name
  • Class Name
  • LinkText
  • Partial LinkText
  • XPath
  • CSS Selector
Few of the examples are:

WebElement eid = driver.findElement(By.id(“email”);

WebElement pswd = driver.findElement(By.name(“password”);

WebElement sbmtBtn = driver.findElement(By.xpath(“//input[@value=”submit”]”);

Types of Fields

To subsequently build the scripts to access forms in Selenium WebDriver, we need to understand the various fields that we will have to handle in our test automation scripts. Let's see how to access these Web elements using Selenium Web Driver with Java. Selenium represents the form element as an object of Web Element. It has an API to find the elements and take action on them like entering text into text boxes, clicking on the buttons, etc. Now we will explore the methods that Selenium makes available to access the form element. Let us try to dig a little more about these WebElements one by one.

Input Box

The input box is a primary element in any form. No form is complete without user input. It can be of two types:

Text Field Box – Text boxes that display the value as is entered by the user.
Password Field Box – Text boxes that display special characters (mostly ‘*’) when the value is entered by the user.
The following image representing the input boxes inside a web form.


Buttons

Buttons are the most important fields to consider while you access forms for Selenium automation testing. There is no point in filling up a form if there is no interface to submit the same. Buttons are simply used to submit whatever information we have filled in our text boxes. This can be submitting some form of data or simply submitting the sign-in information to the server.

CheckBox

In most of the websites that are widely used we see a small box that enables us to check or uncheck it. Mostly in agreement sections wherein the user needs to confirm the understanding of these policies. The checkbox is used to return a boolean value, if it is checked then it would return True else would return false.


Radio Button

A radio button is shown in the form of a circle on any web page. Mostly it is used to show the "Gender" on sign up forms. That is what a radio button is. It is similar to a checkbox only difference being if we are given multiple radio buttons we can select just one, while in the case of multiple checkboxes, we can opt multiple of them.


Link

We all face the common problem of forgetting our account passwords. Noticed the Forgot Password link on the screens? That is what a link is. It redirects us to a new web page or a new window pop-up or a similar thing. It links us to a new URL altogether.

Drop Down

There are times for a website where there are multiple options for a specific category. Say a website to book your flight tickets. To pick up the Origin & Destination city we often see a list with multiple values. This list which has an arrow at the rightmost end to expand and show the values is called a drop-down. It provides a list of options to the user thereby giving access to one or multiple values as per the requirement.


Below is a snapshot of the Facebook Sign up form.

How To Interact With Web Elements

Now, let's see how we access the forms elements in Selenium and how different actions can be performed on each one of them.

Input Box

To handle any input box, we must be able to enter information, clear information, or get information from the box. Selenium offers the following methods to work with text boxes are:

  • sendKeys()
  • clear()
  • getText()
To enter text into a textbox we can use the sendKeys method which would input the user required text from our automation script.

driver.findElement(By.id(“username”).sendKeys(“test@gmail.com”);

The above statement would enter the Email ID as abc@gmail.com into a text box whose ID is username. Now, to clear a pre-entered text or the text that you last entered can be wiped clean with the clear() method.

driver.findElement(By.id(“username”)).clear();

The third method that can be used on a text box is the getText() method. It’ll fetch the text that is written in a text box in case we need to validate some existing or entered text.

String nameText = driver.findElement(By.id(“username”)).getText();

The above line of code would return the text, let us take the text entered by the first line of code above, i.e. test@gmail.com and store it in nameText variable of string type. There might be chances when the text is present in the value property. In such a scenario we will use the getAttribute() method in place of getText().

String nameText = driver.findElement(By.id(“username”)).getAttribute(“value”);

 Buttons

We can submit the information by using buttons. This can be done through click actions on the same. The following are the two methods that are available in selenium to perform actions on the buttons.
  • click()
  • submit()
It might look like there is no difference in both the methods, but a very minute detail changes the usage of each method. Both of these methods would eventually submit the form data to the server, but we need to understand the type of the web element present. If the element type is either ‘submit’ or ‘button’, click() method would work for both, but if the element type is ‘submit’ with the button being inside

driver.findElement(By.id(“submtLogIn”).click();

driver.findElement(By.id(“submtLogIn”).submit();

CheckBox

To interact with checkbox, we’ll use the following Selenium methods:
  • click()
  • isSelected()
To select or check a value we use the click() method. It simply changes the state from unchecked to checked and vice-versa.

driver.findElement(By.id(“name”)).click();

Now that we can check/uncheck a checkbox, we might first need to know the state of a checkbox before performing a certain action with Selenium automation testing. To get the state we use isSelected() method which would return a boolean value. This means if the checkbox is checked we’d get a True else we’ll get False.

boolean state = driver.findElement(By.id(“name”)).isSelected();

Radio Button

The actions performed on the radio button are similar to those on a checkbox and we can use the same methods as above for the radio button as well.
  • click()
  • isSelected()

Link

Links are generally embedded in a web page for us to navigate to a new screen or a popup or a form. We can either do a click action on them or can get the text that it holds and then proceed with our execution.
  • click()
  • getText()
Both of the above methods can be used in a way similar as stated above.

Dropdown

Dropdowns are very commonly and widely used for selecting among a range of options. There is a wide variety of methods that we can use with dropdowns. Let us see them and their corresponding syntax & usage one by one.

selectByVisibleText(String)-  It selects the value from the dropdown by comparing it with visible text, that is passed as a parameter.

selectByIndex(int)- Selects option based on the index in the drop-down menu with integer parameter passed as the index.

selectByValue(String)- It selects the option in the dropdown, based on the value in string format.

In a similar way we can deselect any selected value from the dropdown using any of the below options:

deselectByVisibleText(String)
deselectByIndex(int)
deselectByValue(String)
deSelectAll()

To select an option from the dropdown in selenium, syntax can be as follows:

Select se=new Select(driver.findElement(By.id("nation")));
se.selectByValue("Ind");

To select the single or multiple options some methods are given below:

getAllSelectedOptions()- It is used to get the list of all selected option in the dropdown.
getFirstSelectedOption()- This method would return the first option that has been selected from the dropdown and unlike the above method it would return a single web element and not a list.

getOptions()- This method would enable us to get a list of all available options in a dropdown.

isMultiple()- To check if a dropdown can take multiple options, we can use isMultiple() method which would return a boolean value.

To get a list of options we can write our piece of code by referencing a list object:

Select se=new Select(driver.findElement(By.id("nation")));
List<WebElement> list=se.getOptions();

Now let's try to perform the basic operations and handling of form elements.

Working Example of Form Elements

Here is a practical demonstration of the test script, how to access forms in Selenium.

Facebook Sign up Script

package com.qa.demo.testcases;

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.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestFaceBookForm {

 public static WebDriver driver;

 @BeforeClass
 public static void setUp() {
  //Launch FireFox Browser and Hit the URL
  System.setProperty("webdriver.gecko.driver","/home/khawer/Desktop/geckodriver");
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.get("https://facebook.com");
 }

 @Test
 public void fillForm() {

  // Enter First Name
  WebElement fName = driver.findElement(By.xpath("//input[@name='firstname']"));
  fName.sendKeys("--Enter you name here--");
  
  // Enter Last Name
  WebElement lName = driver.findElement(By.xpath("//input[@name='lastname']"));
  lName.sendKeys("--Enter your last name--");
  
  // We are writing the following two lines just to check the clear function
  lName.clear();
  lName.sendKeys("XYZ");
  
  // Enter Email
  WebElement eMail = driver.findElement(By.xpath("//input[@name='reg_email__']"));
  eMail.sendKeys("--Enter mail or contact number--");
  
  // Enter Password
  WebElement pwd = driver.findElement(By.xpath("//input[@name='reg_passwd__']"));
  pwd.sendKeys("--Enter a valid password here--");
 
  // Select Method for drop downs
  Select date = new Select(driver.findElement(By.xpath("(id('day'))")));
  date.selectByVisibleText("25");
  
  Select month = new Select(driver.findElement(By.xpath("(id('month'))")));
  month.selectByVisibleText("Mar");
  Select year = new Select(driver.findElement(By.xpath("(id('year'))")));
  year.selectByVisibleText("1985");
 
  driver.findElement(By.className("_58mt")).click();

  WebElement sgnUp = driver.findElement(By.xpath("//button[@id='u_0_13']"));
  sgnUp.click();
 }
 @AfterClass
 public static void tearDown() {
  //driver.quit();
 }
}

Java Basics - Lecture 5 - What is Inheritance in Java?

The Hacks of The Day














Inheritance in Java

A process in which one class utilizes the property of another class is called Inheritance. The class that's utilizing the property of another class is called a child class, and therefore the other is called parent class.

It facilitates the code reusability so that a class has to write only the unique features and the rest of the common properties(Data Members) and functionalities(Member Functions) can be extended from another class. Child Class: The class that extends the features of another class is known as child class, subclass or derived class. Parent Class:

The class whose properties and functionalities are inherited by another class is known as a parent class, superclass, or Base class. The process of defining a new class based on an existing class that extends its common data members and methods is called inheritance. Inheritance allows us to reuse code, it improves reusability in your java application.

Note: The main advantage of Inheritance is code reusability, the code that is already present in base class need not be rewritten in the child class.

Syntax: To inherit the properties of a class we use extends keyword. Here class B is child class and class A is parent class. Class B is inheriting the properties and methods of Class A.
class B extends A
{  
}  

Inheritance Example: 

In the following example, we have a base class Shape and a subclass Circle. Since class Circle extends the width and height properties and area() method from the base class, we need not declare these properties and methods in the subclass. Here we have width, height, and area() method which are common to all the shapes so we have declared them in the base class, this way the child classes like Circle, Rectangle and Triangle do not need to write this code and can be used directly from the base class.
class Shape {
   int width = 20;
   int height = 30;
   public void area(){
    System.out.println("Shape");
   }
}
class Circle extends Shape{
    double radius = 40;
    public static void main(String args[]){
    Circle obj = new Circle();
    System.out.println(obj.width);
    System.out.println(obj.height);
    System.out.println(obj.radius);
    obj.area();
   }
}
Output:
20
30
40
Shape
So based on the above example we can say that Circle IS-A Shape. In Java, a child class has an IS-A relationship with the parent class. This is inheritance is known as the IS-A relationship between the child and parent class.

Important Note!! 

The derived class can inherit all the data members and member functions that are declared as public or protected. If the data members or member functions of the superclass are declared as private then the derived class cannot use them directly. The private members are only accessible in its own class. To access private members out of class, getter and setter are used.

Types of Inheritance:

There are different types of inheritance in Java:

  1. Single inheritance
  2. Multiple inheritances
  3. Multilevel inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance


Single inheritance: In single inheritance, a derived class is created from one parent class. It refers to a child and parent class relationship where a class extends another class. Syntax:
//Parent Class
class Parent 
{
   //methods and fields  
}
//Child Class
class childClass extends Parent
{  
   //methods and fields  
}
Let's take an example. Suppose we have a parent class "Vehicle" and child class "Car". Child class will acquire the features of the parent class. As shown in the main method we have created an object of the child class, this object will call the methods of both classes (Child & Parent)
class Vehilce {
 public void engine() {
  System.out.println("engine...");
 }
}
class Car extends Vehicle {
 public void start() {
  System.out.println("start...");
 }
}
public class ExecuteClass {
 public static void main(String args[]) {
  Car c = new Car();
  c.engine();
  c.start();
 }
}
Multiple inheritances: In multiple inheritance one class extending more than one class, which means One child class has two parent classes. As per the above diagram, Class C extends Class A and Class B both.

Multilevel inheritance: In multilevel inheritance, one class can inherit from the child class. Hence, the child class becomes the parent class for the new one. As shown in the below diagram Class C is a child of Class B and B is a child class of Class A.

Hierarchical Inheritance: In hierarchical inheritance, more than one classes extend one class. In the below diagram Class B, C, and D inherit the same class A.

Hybrid Inheritance: Hybrid inheritance is a combination of Single and Multiple inheritances in a single program. As per the below example, all the public and protected members of Class A are inherited into Class D, via Class B and Class C.

Note: Java doesn't support hybrid/Multiple inheritances

Constructors and Inheritance: 

When you create an object of a child class, it's constructor is called, it by default invokes the superclass class default constructor. In inheritance, constructors are called in a top-down approach.

A SuperClass constructor is called by using super keyword. The super keyword refers to the superclass, immediately above the calling class in the hierarchy. To access the data members or methods of the parent class super keyword is used.
class ParentClass{
   //Parent class constructor
   ParentClass(){
    System.out.println("Constructor of Parent");
   }
}
class ChildClass extends ParentClass{
   ChildClass(){
    
    System.out.println("Constructor of Child");
   }
   public static void main(String args[]){
    //Creating the object of child class
    new ChildClass();
   }
}
Output:
Constructor of Parent
Constructor of Child

Inheritance and Method Overriding: 

To declare the same method in child class which is already present in the parent class then this is called method overriding. In this case, when we call the method from the child class object, the child class version of the method is called. However, we can call the parent class method using the super keyword as I have shown in the example below:
class ParentClass{
   //Parent class constructor
   ParentClass(){
    System.out.println("Constructor of Parent");
   }
   void disp(){
    System.out.println("Parent Method");
   }
}
class ChildClass extends ParentClass{
   ChildClass(){
    System.out.println("Constructor of Child");
   }
   void disp(){
    System.out.println("Child Method");
        //Calling the disp() method of parent class
    super.disp();
   }
   public static void main(String args[]){
    //Creating the object of child class
    ChildClass obj = new ChildClass();
    obj.disp();
   }
}

Summary: 

Inheritance means to inherit the properties from parent. A child can inherit all properties from the parent. A parent can have multiple children. A child can have only one parent. When the method is present in the parent class as well as in child class with the same name and same parameters – Method Overriding. Preference will be given to the overridden method. The super keyword is used to access parent class features.

Java Basics - Lecture 4 - What is class and object in Java

The Hacks of The Day
Java Class and Object

This lecture will cover basic OOP concepts. What is Class and Object? What is the difference between them?

Lecture 4 Agenda


1) Class
2) Object

Classes and objects are the fundamental parts of OOP. In OOP, we try to map real-world entities into software objects. Although there is a confusion between object and class, in this article, we will try to explain the difference between object and class. First, let's understand what they are.

What is a class?

A class is a blueprint or template for objects. It defines the behavior of objects. It determines how an object will behave and what the object will contain. In other words, a set of instructions to build a specific type of object.

Syntax:

public Class {
 Data Members;
 Member Functions;
}

Class Components:

Access Modifiers: A class can be public or has default access.
Class Name: The class name begins with a Capital letter.
Class Body: The class body is shown by curly braces, { }. It contains data members and member functions.

What is an Object?

An object is an entity with some attributes and behavior. When we look around, we see many examples of real-world objects: dog, desk, television, bicycle, etc. The real-world objects have two characteristics one is called "state" and the other is "behavior".

For example, dogs have state (name, color, breed, age, size) and dogs have behavior (barking, eating, running, sleeping). In terms of Software objects, they also have state and behavior.

Remember: To create an object of a class"new" keyword is used.

Syntax:
ClassName ReferenceVariable = new ClassName();

An object consists of :

State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by methods of an object. It also shares the response of an object with other objects.
Identity: It assigns a unique name to an object and enables one object to interact with other objects.

When an object of a class is created the class is called instantiated. All the instances share the attributes and the behavior of the class, the state will be different for each object. A single class can have more than one instance. As shown in the below image.

What is object and class in Java

Let's take an example of a class Car. Below is the Java code for this class.
//Class Declaration

public class Car {
 // Instance Variables
 int model;
 int wheel;
 String color;
 // Member Function
 public String getInfo() {
  return ("Modal is: " + model + " Wheels are: " + wheel + " Color is: " + color);
 } 
 public static void main(String[] args) {
  Car car = new Car();
  car.model = 2015;
  car.wheel = 4;
  car.color = "while";
  System.out.println(car.getInfo());
 }
}
Output: 

Modal is: 2015 Wheels are: 4 Color is: white

In the above example, we created one reference variable (car) and assigned a new instance of the Car class to this variable. Such an object is also called an instance of the class.

Summary:

A class is a user-defined blueprint or template from which objects are created. It determines how an object will behave and what the object will contain.
A Java object consists of methods and properties to make a certain type of data useful.
A class system allows the program to define a new class (child class) in terms of an existing class (parent class) by using a technique like inheritance, Polymorphism, and overriding.

How to find XPath in Selenium WebDriver?

The Hacks of The Day
How to find XPath in Selenium WebDriver?


What is XPath? 

It is a syntax or language for finding the web elements on the web page from an XML document. XPath is used to find the location of any element on a web page using the HTML DOM structure. The Syntax for XPath: The below diagram is showing the format and elements of XPath. It helps to find the complex, dynamic web elements which are not accessible with common locator like ID, Name, CSSSelectors, etc.

XPath=//tagname[@attribute='value']

// : Select current node.
Tagname: Tagname of the particular node.
@: Select attribute.
Attribute: Attribute name of the node.
Value: Value of the attribute.

How to get XPath in Chrome: 

  1. Open the required URL in google chrome browser.
  2. Inspect the required element
  3. Right-click on the selected element
  4. Navigate to Copy -> Copy Full XPath (Absolute XPath)
  5. Navigate to Copy -> Copy XPath (Relative XPath)

Types of XPath: 

XPath has the following two types. Let's explain one by one to get deep understanding of XPath

1- Absolute XPath
2- Relative XPath 

Absolute Xpath: 

The Xpath that is used to find the element from the root node is called absolute XPath. The absolute XPath starts with a single slash(/). It contains the whole DOM structure starting from the root node to the node that we are going to find. The disadvantage of the absolute XPath is that when some changes are made in the path of the element, then that element could not be accessible anymore. Below is the example of absolute XPath.
Absolute XPath: /html/body/div[1]/div/div/form/div/div[1]/div/input

Relative XPath: 

It does not start from the root node. It starts finding the elements from the middle of the DOM structure. Double forward slash(//) is used to find the relative XPath. It can search the element anywhere on the web page. Below is the example of relative XPath.
Relative xpath: //*[@id="ui"]/div/div/form/div/div[2]/div/input
XPath finding with different locators. Given below are the possible ways to find the XPath.

1) Find By Id: 

Suppose we have the following HTML structure for an element. We can find the XPath by ID because the ID attribute is available.
Xpat h= //input[@id='email'] or we can also use as //*[@id='email']

2) Find By Name:  

If you want to find the XPath by Name attribute then the XPath expression will look like be as given below. Some time "id" attribute is not available in HTML structure for the required element. Then we can use "Name" attribute
XPath=//input[@name='email'] or we can also use as //*[@name='email']
Here is a link of the page https://ui.cogmento.com/

3) Find By Class Name: 

You can also find the XPath by Class Name. Given below is the example of XPath by Class Name.
XPath = //h2[@class='barone']

4) Find By Text() Method:

This method is used to find the element with exact text matching. In our case, we find the element with the text "Login".
XPath = //div[text()='Login']

5) Find By Contains() Method:

Contains() method is used in XPath expression to find the web elements with partial text matching. In the below example we have tried to find the element with partial text. In the XPath expression, you can see the text "Sign" in place of "Sign Up" But we can't find this element with the Text() method directly, because it only works with full-text matching.

XPath = //a[contains(text(),'Sign')] // Full Name Sign Up
Xpath = //*[contains(@type,'btn')] // Full Name btnLogin
If we use text() method with partial text as given below, it will not work.
XPath = //a[text(),'Sign')]

6) Find By Child: 

In the following XPath expression, we have found the child element "a" of the h4 tag. We can not find the "a" tag directly with the text "Java" because some other elements have the same text. So we have started with the top parent div of "a" tag.
XPath = //div[@class='g-block box4 size-24 hidden-phone']
//div[@class='g-content g-particle']//div[@class='canvas-graph']
//div[@class='canvas-middle']//h4//a[text()='Java']

7) Find By Preceding Sibling: 

In the preceding sibling, we can find the nodes that come before the current node, but the level should be the same. In some cases to find an element, we need to do some reverse engineering. We move from bottom to top to find the required element. To click in the checkbox, we will find the name that comes in front of a checkbox.
XPath = //td[text()='Tom Peter']
//preceding-sibling::td//div[@class='ui fitted read-only checkbox']
//input[@name='id']

8) Find By the Following Sibling: 

In the following sibling, we can find the nodes that come after the current node, but the level should be the same. One thing, that you should remember in the following sibling only one forward-slash (/) is used before the keyword (following-sibling). But in the case of preceding sibling double forward-slash (//) is used.
XPath = //div[@class='canvas-middle']
//a[contains(@href, 'http://www.guru99.com/accounting.html')]
/following-sibling::h4//a[text()='ACCOUNTING']

9) Find By Parent: 

It selects the parent of the current node, as shown in the below image.
XPath = //td[text()='Tom Peter']//parent::tr
//td//div[@class='ui fitted read-only checkbox']
//input[@name='id']

10) Find By Starts-with & Ends-with Methods: 

To find the XPath of the dynamic web element, whose attribute value changes on refresh, we will use either Starts-with or Ends-with method. Suppose id of an element is changing dynamically like: Id = message_123 Id = message_234 Id = message_544 So on... In the above examples, initial text is the same (message) but numerical values keep changing. So Starts-with function will be used.
XPath = //input[starts-with(@id,'message_')]
Similarly, we can use the Ends-with method. But it can be used, where the last value remains the same, and the initial value keeps changing. Suppose id of an element is changing dynamically like: Id = 234_test_t Id = 456_test_t
XPath = //input[ends-with(@id,'_test_t')]

Conclusion: 

To find the element by XPath is much more efficient as compared to other locators. That's why in complex projects, Automation Engineers prefer to use XPath for finding the elements. You can use it in a versatile way. You can find an element by moving from child to parent or parent to child. You can navigate to any direction in the HTML DOM structure. You can also control the dynamic values of web elements.