Selenium WebDriver Commands and Operations

Selenium WebDriver Commands and Operations

> Selenium WebDriver Methods are used to perform operations on Web Elements.

> Using Element Locators and WebDriver Methods we create Test Cases.

Element Locators - for recognizing Elements

WebDriver Methods - for performing operations on Elements.
-----------------------------------

WebDriver Methods

1) get()
Description: Opens a specified URL in the Browser window.

Syntax:

driverObject.get("URL");

Example:

driver.get("https://www.google.co.in");
------------------------------------
2) getTitle()
Returns Title of the Browser.

Syntax:

String variable = driver.getTitle();

Example:

driver.get("https://www.google.co.in");
String Title = driver.getTitle();
System.out.println(Title);
------------------------------
3) getPageSource()
Returns HTML page source.

Syntax:

String stringName = driver.getPageSource();

Example:

driver.get("https://www.google.co.in");
String pageSource = driver.getPageSource();
System.out.println(pageSource);
------------------------
4) getCurrentUrl();
Returns Current URL of the Browser.

Syntax:

String stringName = driver.getCurrentUrl();

Example:
driver.get("https://www.google.co.in");
String URL = driver.getCurrentUrl();
System.out.println(URL);
-------------------------------
Browser Navigation Methods
5) navigate().to();
Loads a new web page in the current browser window.

Syntax:
driverObject.navigate().to("URL");

Example:

driver.get("https://www.google.co.in");
String URL = driver.getCurrentUrl();
System.out.println(URL);
driver.navigate().to("https://login.yahoo.com/");
URL = driver.getCurrentUrl();
System.out.println(URL);
-------------------------------------
6) navigate().back()
It moves a single item back in the Browser history.

Syntax:

driver.navigate().back();

Example:

driver.get("https://www.google.co.in");
String URL = driver.getCurrentUrl();
System.out.println(URL);
driver.navigate().to("https://login.yahoo.com/");
URL = driver.getCurrentUrl();
System.out.println(URL);
driver.navigate().back();
URL = driver.getCurrentUrl();
System.out.println(URL);

Or

driver.get("https://www.google.co.in");
String URL = driver.getCurrentUrl();
System.out.println(URL);
driver.navigate().to("https://login.yahoo.com/");
URL = driver.getCurrentUrl();
System.out.println(URL);
driver.navigate().to("https://www.google.co.in");
URL = driver.getCurrentUrl();
System.out.println(URL);
-----------------------------------
7) navigate().forward();
It moves single item forward in the Browser history.

Syntax:

driver.navigate().forward();

Example:

driver.get("https://www.google.co.in");
String URL = driver.getCurrentUrl();
System.out.println(URL);

driver.navigate().to("https://login.yahoo.com/");
URL = driver.getCurrentUrl();
System.out.println(URL);

driver.navigate().back();
URL = driver.getCurrentUrl();
System.out.println(URL);

driver.navigate().forward();
URL = driver.getCurrentUrl();
System.out.println(URL);

Or

driver.get("https://www.google.co.in");
String URL = driver.getCurrentUrl();
System.out.println(URL);

driver.navigate().to("https://login.yahoo.com/");
URL = driver.getCurrentUrl();
System.out.println(URL);

driver.navigate().to("https://www.google.co.in");
URL = driver.getCurrentUrl();
System.out.println(URL);

driver.navigate().to("https://login.yahoo.com/");
URL = driver.getCurrentUrl();
System.out.println(URL);
-----------------------------------
8) navigate().refresh()
Refresh the current web page

Syntax:

driver.navigate().refresh()

WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in");
String URL = driver.getCurrentUrl();
System.out.println(URL);
driver.navigate().refresh();
URL = driver.getCurrentUrl();
System.out.println(URL);
------------------------------------
Method Syntax in Java

Object.method();
Object.property().method();
Class.method();
-----------------------------------
9) close()
It closes the focused Browser.

Syntax:

driverObject.close();

Example:

driver.get("https://www.google.co.in");
driver.close();
-----------------------------------
10) quit()
It closes all browser that opened by WebDriver during execution.

Syntax:

driverObject.quit();

Example:

driver.get("file:///C:/Users/gcreddy/Desktop/HTMLExamples/LoginPage.html");
driver.findElement(By.linkText("Sign In")).click();
driver.quit();
-----------------------------------
11) findElement()
It finds the first element within the current page using the give locator.

driver.findElement(By.ElementLocator("Value"))

Syntax:
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/gcreddy/Desktop/HTMLExamples/LoginPage.html");
driver.findElement(By.tagName("input")).sendKeys("abcd");

Or

WebElement Email = driver.findElement(By.id("Email"));
Email.sendKeys("India");
-----------------------------------
12) sendkeys()
Enters a value into Edit box/Text box

Syntax:
driver.findElement(By.ElementLocator("value").sendkeys("input data");

Example:

driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys("India");
}
-----------------------------------
13) clear()
It clears the value

Syntax:
driver.findElement(By.ElementLocator("value").clear();

Example:
driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys("India");
Thread.sleep(5000);
driver.findElement(By.id("Email")).clear();
-----------------------------------
14) click()
Clicks an Element (Buttons, Links)

Syntax:

driver.findElement(By.ElementLocator("value").click;

Example:

driver.get("https://www.gmail.com");
driver.findElement(By.id("next")).click();
-----------------------------------
15) isEnabled()
It checks weather the Element is in enabled state or not?

Syntax:

boolean variableName = driver.findElement(By.ElementLocator("value").isEnabled();

Example:

driver.get("https://www.gmail.com");
boolean a = driver.findElement(By.id("next")).isEnabled();
System.out.println(a);
-----------------------------------
16) isDisplayed()
Checks if the Element is displayed or not? in the current web page.

Syntax:

boolean variableName = driver.findElement(By.ElementLocator("value").isDisplayed();

driver.get("https://www.gmail.com");
boolean a = driver.findElement(By.id("next")).isDisplayed();
System.out.println(a);
-----------------------------------
17) isSelected()
checks if the Element is Selected or not? in the current web page.

Syntax:

boolean variableName = driver.findElement(By.ElementLocator("value").isSelected();

Example:

driver.get("file:///C:/Users/gcreddy/Desktop/HTMLExamples/MultipleCheckbox.html");
boolean a = driver.findElement(By.xpath("html/body/input[2]")).isSelected();
System.out.println(a);//false
driver.findElement(By.xpath("html/body/input[2]")).click();
a = driver.findElement(By.xpath("html/body/input[2]")).isSelected();
System.out.println(a);//true
-----------------------------------
18) manage().window().maximize()
Syntax:

driverObject.manage().window().maximize()

Example:

driver.get("file:///C:/Users/gcreddy/Desktop/HTMLExamples/MultipleCheckbox.html");
Thread.sleep(5000);
driver.manage().window().maximize();
-------------------------------------------

Web Elements and Element Locators

Web Elements and Element Locators
 

i) Web Elements

ii) Element Locators
---------------------------------------
i) Web Elements
Browser
Page
-----------------
Edit Box
Link
Button
Image, Image Link, Image Button
Text box
Text Area
Check box
Radio Button
Drop down box
List box
Combo box
Web table /HTML table
Frame
-----------------------------------
1) Operations on Browser
> Launch the browser,
> Navigate to particular web page,
> Close focused Browser
> Close all Browsers that opened by WebDriver during execution
---------------
> Navigate from one URL to another
> Navigate back to previous URL
> Navigate forward
> Refresh the Browser
> Maximize the Browser
Etc...
-----------------------------------
2) Operations on Web Page
> Get Page Title
> Get Page URL
-----------------------------------
3) Operations on Edit box

> Enter a Value,
> Clear the Value,
> Check enabled status,
> Check edit box existence,
> Get the value etc...
-----------------------------------
4) Operations on Link

> Click Link,
> Check the link existence,
> Check the link enabled status,
> Return the Link Name
Etc...
-----------------------------------
5) Operations on Button

> Click
> Check Enabled status
> Display status
Etc...
-----------------------------------
6) Operations Image

Three types of Image elements in Web Environment

a) General Image (No functionality)

b) Image Button (Submits)

c) Image Link (Redirects to another page/location)
-----------------------------------
7) Operations on Text Area

> Return / Capture Text Area or Error message from a web page
-----------------------------------
8) Operations on Check box

> Check if the check box is displayed or not?
> Check if the check box is enabled or not?
> Check if the check box is Selected or not?
> Select the Check box
> Unselect the Check box
-----------------------------------
9) Operations on Radio Button

> Select Radio Button
> Verify if the Radio Button is Displayed or not?
> Verify if the Radio Button is enabled or not?
> Verify if the Radio Button is Selected or not?
------------------------------------
10) Operations on Drop down box

> Check the Drop down box existence
> Check if the Drop down is enabled or not?
> Select an item
> Items Count
-----------------------------------
11) Operations on List box

12) Operations on Combo box
-----------------------------------
13) Operations on Web table /HTML Table

> Get cell value
> Rows Count
> Cells Count Etc...
-----------------------------------
14) Operations on Frame
-----------------------------------
> Switch from Top window to a frame
> Switch from a frame to Top window
Etc...
----------------------------------------------
ii) Element Locators
What is Locator?

> Locator is an address that identifies a web element uniquely within the webpage. Locators are the HTML properties of a web element.

Selenium WebDriver uses 8 element locators

id,

name,

className,

tagName,

linkText,

partialLinkText,

cssSelector,

xpath

to find elements on Web pages.

Why we need to use different locators?

1) Developers may not provide all locators for all elements

2) Some locators may be duplicated.

So we have to choose any one unique locator to recognize the element.

How to inspect elements?

Download and install Firebug and Firepath plug ins/Add ons for Firefox Browser.

If it Internet Explorer or Chrome, we no need to install any Add on, they provide built -in Developer Tools (F12) to inspect elements.

Element Locators are common for all Browsers.
-----------------------------------------
1) id

Syntax:

By.id("id value")

Examples:

driver.findElement(By.id("Email"))

driver- is Object

findElement - WebDriver method

By - pre-defined Class

id - Element locater

Email - id locator value
-------------------------------------
driver.findElement(By.id("Email")).sendKeys("gcrindia");
--------------------------------------------
Or

WebElement Email = driver.findElement(By.id("Email"));
Email.sendKeys("gcrindia");
-------------------------------------------
id locator for Button

WebElement Email = driver.findElement(By.id("signIn"));
Email.click();

Or

driver.findElement(By.id("signIn")).click();
-------------------------------------------------------
2) name

Synatx:

By.name("name value/locator name")      

Examples:

driver.findElement(By.name("Email")).sendKeys("gcrindia");
      
Or

WebElement e = driver.findElement(By.name("Email"));
e.sendKeys("gcrindia");
------------------------------------------
WebElement e = driver.findElement(By.name("signIn"));
e.click();
------------------------------------------
3) className

Syntax: By.className("class name value")

Example:

driver.findElement(By.className("textboxcolor")).sendKeys("Hyderabad");
----------------------------------------------
4) tagName

Syntax:
By.tagName("tag name value")

Example:
driver.findElement(By.tagName("input")).sendKeys("Hyderabad");
--------------------------------------------------------------      
5) linkText

Syntax:
By.linkText("Link Text Value")

Example:

driver.findElement(By.linkText("Gmail")).click();
-----------------------------------------------------              
6) paritialLinkText

Syntax:
By.partialLinkText("Partial Link Text Value")

Example:

driver.findElement(By.partialLinkText("Gma")).click();
-----------------------------------------------
7) cssSelector
Syntax:
By.cssSelector("value")

Example:
driver.findElement(By.cssSelector(".gb_m")).click();
---------------------------------------------------
8) xpath
Xpath in XML document shows the direction of software web application's element location.

Syntax:

By.xpath("xpath value")

driver.findElement(By.xpath(".//*[@id='Email']")).sendKeys("abcdef");
------------------------------------------------------------------------------

Introduction to Selenium WebDriver

Introduction to Selenium WebDriver

i) Introduction to Selenium WebDriver

ii) WebDriver Environment Setup

iii) Create first Selenium Test Case
-------------------------------------------
i) Introduction to Selenium WebDriver
Selenium Tool’s Suite
        Selenium IDE
        Selenium RC
        Selenium WebDriver
        Selenium Grid

> In 2006 Selenium WebDriver was launched at Google.

> In 2008, the whole Selenium team decided to merge Selenium WebDriver with Selenium RC in order to form more powerful tool called Selenium 2.0

Selenium 1.0 + WebDriver = Selenium 2.0

Selenium 1.0

(Selenium IDE + Selenium RC + Selenium Grid)

Selenium 2.0

(Selenium IDE + Selenium RC + Selenium WebDriver + Selenium Grid)

Note: Now Selenium RC is only for maintenance projects.
----------------------
> It is a most important tool in Selenium Suite.

> It has Programming interface only, no IDE.

> Selenium WebDriver supports various programming languages to write programs (Test scripts)

Java
Python
C#
Ruby
Perl
PHP

> Selenium WebDriver supports various Browsers to create and execute Test cases.

Mozilla Firefox

Google Chrome

IE

Safari

Opera etc...

> Selenium WebDriver supports various Operating environments.

MS Windows

Linux

Macintosh etc...

> Selenium WebDriver supports Data driven Testing and Cross browser testing.

> Selenium WebDriver is faster than other tools of Selenium suite.

> Selenium WebDriver supports Parallel test execution with the help of either JUnit or TestNG.
-------------------------------
Drawbacks of selenium Webdriver
> Selenium WebDriver doesn't have IDE (some difficult to create test cases)

> No Built-in Result reporting facility.

> No other tool Integration for Test management.

> No centralized maintenance of Elements/objects.
--------------------------------------------------
How we create Test Cases /Test Scripts / Tests in Selenium WebDriver:
In UFT:

Using Objects information and Test Methods we create Tests.

In Selenium WebDriver:

Using Element Locators and Webdriver Commands/methods we create Test Cases.

Selenium IDE:

Using Element locators and Selenese / Selenium IDE commands we create Test cases
-----------------------------------
Element Locators - to recognize elements/identify elements.

WebDriver commands/methods - to perform operations on elements.
--------------------------------------
Java Programming - for enhancing Test Cases

TestNG Framework - for grouping Test cases, batch Testing and generating Test Reports.
-----------------------------------------------------------
ii) Selenium WebDriver Environment Setup.
Steps:

1) Download and Install Java (JDK) software -to create programs (Test scripts)

2) Set Environment variable (path variable).

3) Download Eclipse IDE and extract - to write and execute Java programs.

4) Download Webdriver Java language binding (www.seleniumhq.org) and add WebDriver jar files to Java project in Eclipse IDE.
---------------------------------------
5) Install Firebug and Firepath plug ins (Mozilla Firefox) for inspecting elements.

6) For Internet Explorer and Google Chrome, no need to install any plug in, they have
built in developer tools(F12) for inspecting elements.

7) Firefox driver is default driver in Seelenium Webdriver, for IE and Chrome etc... Browsers then we need to download browser drivers.
--------------------------------------------
Download Selenium WebDriver Java language binding from www.seleniumhq.org website and extract.

Add WebDriver jar files to Java Project in Eclipse IDE
Navigation:

Create Java Project

> Select Java project and right click

> Build path

> Configure build path

> Select "Libraries" tab

> Click "Add external Jars"

> Browse path of the WebDriver jars.

> Add
-----------------------------------------
Create Selenium WebDriver Test Case
> Import Webdriver and Firefox/IE/Chrome Libraries. (In Selenium Test Case/Program)

> Using Element locators and Webdriver commands write test steps.

> Insert java programming statements to enhance Test cases.
-----------
> Using TestNG Annotations group test cases, execute test batches and generate detailed test reports.
--------------------------------------------------
iii) Write first Selenium Test Case
Manual Test Case
Test Case ID: gcrshop_admin_TC001

Test Case Name: Verify Admin Login in GCR shop Web Portal

Test Steps:

1) Launch the Browser and navigate to "www.gcrit.com/build3/admin"
2) Enter User name
3) Enter Password
4) Click Login Button

Input data:

Username = admin
Password =admin@123

Expected URL: "www.gcrit.com/build3/admin/index.php"

Actual: http://www.gcrit.com/build3/admin/index.php

Test Result: Pass
-------------------------------------------
* Verification point: Capture the Browser URL after submission of Login details and compare with expected URL.
----------------------------------------------------------------
Selenium WebDriver Test Case:
public class AdminLogin {

public static void main(String[] args) {
WebDriver driver = new FirefoxDriver(); //Launches Firefox Browser with blank url
driver.get("http://www.gcrit.com/build3/admin/login.php");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin@123");
driver.findElement(By.id("tdb1")).click();

String url = driver.getCurrentUrl();
if (url.equals("http://www.gcrit.com/build3/admin/index.php")){
System.out.println("Login Successful -Passed");   
}
else
{
System.out.println("Login Unsuccessful -Failed");       
}
driver.close(); //Closes the Browser
}
}
----------------------------------------------------

Java Abstraction and Encapsulation

Java Abstraction and Encapsulation
 

Java Object Oriented Programming

i) Inheritance

ii) Polymorphism
----------------
iii) Abstraction

iv) Encapsulation
--------------------------------------
Abstraction

> It is a process of hiding implementation details and showing only functionality to the user.

Two types of Methods in Java

1) Concrete Methods (The methods which are having body)

Example:

public void add(){
Statements
---------
--------
-----------
}

2) Abstract Methods (The methods which are not having body)

Ex:

public void add();

--------------------------------------
> If we know the method name, but don't know the method functionality, then we go for Abstract methods.

> Java Class contains 100% concrete methods.

> Abstract class contains one or more abstract methods.
--------------------------------------

Example:

Class 1 (having 10 methods)

10 methods are concrete methods

It is a Java Class

Class 2 (having 10 methods)

(5 concrete methods and 5 abstract methods)

Abstract class

Class 3 (having 10 methods)

(All 10 methods are abstract methods)

Abstract class
----------------------------
Example:

Abstract Class

public abstract class Bike {

public void handle(){
System.out.println("Bikes have Handle");
}

public void seat(){
System.out.println("Bikes have Seats");
}

public abstract void engine();

public abstract void wheels();

public static void main (String [] args){
HeroHonda obj = new HeroHonda();
obj.engine();
obj.wheels();
}
}
----------------------------------
Sub Class

public class HeroHonda extends Bike{
@Override
public void engine() {
System.out.println("Bikes have Engine");
}

@Override
public void wheels() {
System.out.println("Bikes have Wheels");
}

public static void main (String [] args){
//Create Object
HeroHonda objHH = new HeroHonda();   
objHH.engine();
objHH.seat();
objHH.wheels();
objHH.handle();
}
}
--------------------------
Interfaces

Selenium IDE has User Interface (Integrated Development Environment)

Selenium WebDriver is a Programming Interface.
---------------------------
UFT/QTP has both IDE as well as Programming Interface.
------------------------------
Java Interfaces

> Interface is a Java type definition block which is 100% abstract

> All the Interface methods by default public and abstract.

> static and final modifiers are not allowed for interface methods.

> In Interfaces variables have to initialize at the time of declaration.

int a;//Incorrect

int a =10; //Correct

> In Interfaces variables are public, static, and final by default.

> Interface is going to be used using "implements" keyword.
---------------------------------------------------
Example for Java Interface:

1) Create an Interface

public interface Interface1 {
public void engine();
public void wheels();
public void seat();
public void handle();

public static void main (String [] args){
ClassNew objx = new ClassNew();   
objx.engine();
objx.wheels();
}
}

2) Reuse Methods from Interface to Class

public class ClassNew implements Interface1{

   
public void engine() {
System.out.println("Bikes have Engine");
}
   
public void wheels() {
System.out.println("Bikes have Wheels");
}

   
public void seat() {
System.out.println("Bikes have Seats");
}

public void handle() {
System.out.println("Bikes have Handle");
}

public static void main (String [] args){
ClassNew obj = new ClassNew();
obj.seat();
obj.wheels();
obj.engine();
obj.handle();
}
}
---------------------------------------------
Note:

From Class (Concrete class or Abstract Class) to Class we use "extends" keyword

From Interface to Class we use "implements" keyword
-----------------------------------
Encapsulation:

It is a process of wrapping code and data into a single unit.

Encapsulation is the technique making the fields in a class private and providing access via public methods.

> It provides control over the data.

> By providing setter and getter methods we can make a class read only or write only.

Example:
Class1:

public class Class1 {
private String name = "Test Automation";

public String getName(){
return name;
}
public void setName(String newName){
name=newName;   
}

public static void main (String [] args){
Class1 obj = new Class1();
System.out.println(obj.getName());
}
}
--------------------------------
Class2:
public class Class2 extends Class1 {

public static void main(String[] args) {
Class2 obj2 = new Class2();
obj2.setName("Selenium");
System.out.println(obj2.getName());
}
}
--------------------------------------
Java for Selenium

Java Environment setup
Java Program Structure
A) Java Fundamentals
    1) Comments in Java
    2) Data Types
    3) Modifiers
    4) Variables
    5) Operators
    6) Flow Control
        Conditional Statements
        Loop Statements
    8) Arrays
    9) String Handling in Java
    10) I/O operations and File handling
    11) Java Methods
        Built in methods
        User defined methods
    13) Exception handling
-------------------------------
B) Java OOPS

    1) Inheritance
    2) Polymorphism
    3) Abstraction
    4) Encapsulation
----------------------------------------------

Java Inheritance and Polymorphism


Java Inheritance and Polymorphism

Java OOPS- Object Oriented Programming System.

Four fundamentals OOPS:

i) Inheritance

ii) Polymorphism

iii) Abstraction

iv) Encapsulation
-----------------------------
i) Inheritance
 

> It is a process of Inheriting(reusing) the class members(Variables and Methods) from one class to another.

> Non-static class members only can be Inherited.

> The class where the class members are getting Inherited is called as Super class/Parent class/Base class.

> The class to which the class members are getting Inherited is called as Sub class/Child class/derived class.

> The Inheritance between Super class and Sub class is achieved using "extends" keyword.
--------------------------------------------------------
How to create Static class members?
Using static Non-access modifier.

How to access Static class members?
Using Class Name we access Static class members.

How to access Non static class members?
Using Object/Instance we can access Non static class members.
------------------------------------------------------
Example for accessing Static and Non-static Class members:
 

package package1;

public class Class1 {
//Declare Static variables

static int a =10, b=20;
//Declare Non-static variables

int c=30, d=40;
//Create Static a method with returning a value

public static int add(){
int result = a+b;
return result;   
}
//Create Static a method without returning any value

public static void multiply(){
System.out.println(a*b);
}
//Create a Non static method with returning a value

public int add2(){
int res = c + d;
return res;
}
//Create a Non static method without returning any value 

public void multiply2(){
System.out.println(c*d);   
}
public static void main (String [] args){
//Access Static Class Members(Using Class Name)

int x = Class1.add();
System.out.println(x);//30
System.out.println(Class1.a);//10
Class1.multiply();//200

//Access Non static class members(Using Object) 

Class1 obj = new Class1();
int y = obj.add2();
System.out.println(y);//70
System.out.println(obj.c);//30
obj.multiply2();//1200
}
}
-----------------------------
Three types Inheritance
 

1) Single Inheritance
 

Example:
public Class ClassB extends Class A {
.
}
-----------------------
2) Multi level Inheritance
 

Example:
public Class ClassB extends ClassA {

public Class ClassC extends ClassB {
----------------------------------
iii) Multiple Inheritance (* Java doesn't support)
Example:

public class ClassB extends ClassA {
public class ClassB extends ClassD {
.
.
}
}
--------------------------------------------
Example for Inheritance:
 

Class 1:
public class ClassA {
int a =10;
int b =20;
public void add(){
System.out.println(a+b);
}

public static void main(String[] args) {
ClassA objA = new ClassA();
System.out.println(objA.a);//10
objA.add();//30
}
}
----------------------------
Class 2:
public class ClassB extends ClassA{
int a =100;
int b =200;
public void add(){
System.out.println(a+b);   
}
public static void main(String[] args) {
ClassB objB = new ClassB();
objB.add();//300
System.out.println(objB.a);//100
}
}
----------------------------
Class 3:
public class ClassC extends ClassB {
int a =1;
int b=2;
public void add(){
System.out.println(a+b);
}

public static void main(String[] args) {
ClassC objC = new ClassC();
System.out.println(objC.a);
objC.add();
}
}
--------------------------------------
Example 2:
package package1;

public class ClassX {
protected int a =10;
protected int b =20;

protected void add(){
System.out.println(a+b);
}
public static void main(String[] args) {
ClassX objX = new ClassX();
System.out.println(objX.a);
objX.add();
}
}
---------------------------------
package package2;

import package1.ClassX;

public class ClassZ  extends ClassX{
public static void main(String[] args) {
ClassZ objZ = new ClassZ();
objZ.add();
System.out.println(objZ.a);
}
}
-----------------------------
ii) Polymorphism
 

Existence of Object behavior in many forms

There are two types of Polymorphism

1) Compile Time Polymorphism / Method Overloading

2) Run Time Polymorphism or Method Overriding
-----------------------------------
1) Compile Time Polymorphism / Method Overloading
 

If two are more methods having same name in the same class but they differ in following ways.

a) Number of Arguments

b) Type of Arguments
-----------------------------
Example for Method OverLoading:
 

public class MethodOverLoading {
public void add(int a, int b){
System.out.println(a+b);   
}

public void add(int a, int b, int c){
System.out.println(a+b+c);   
}

public void add(double a, double b){
System.out.println(a+b);   
}

public void add(double a, double b, double c){
System.out.println(a+b+c);   
}
public static void main(String[] args) {
MethodOverLoading obj = new MethodOverLoading();
obj.add(10, 20);
obj.add(10, 20, 30);
obj.add(1.234, 2.456);
obj.add(1.234, 2.456, 3.567);
}
}
-----------------------------------------
2) Run Time Polymorphism or Method Overriding
 

If two are more methods with same name available in the Super class and Sub class.

Example for Method OverLoading:
Class 1:


public class ClassNew1 {
public void myMethod(){
System.out.println("Selenium for Test Automation");
}
public static void main(String[] args) {
ClassNew1 obj = new ClassNew1();
obj.myMethod();
}
}
-------------------------

Class 2:
 
public class ClassNew2 extends ClassNew1{
public void myMethod(){
System.out.println("UFT for Test Automation");
}
public static void main(String[] args) {
ClassNew2 obj = new ClassNew2();
obj.myMethod();//UFT for Test Automation

ClassNew1 obj2= new ClassNew1();
obj2.myMethod();//Selenium for Test Automation
}
}
-----------------------------------------------

Java Variables and Operators

Java Modifiers, Variables and Operators
 

i) Modifiers in Java

ii) Java Variables

iii) Java operators
-----------------------------
i) Modifiers in Java
Modifiers are keywords that we add to those definitions to change their meaning.

a) Access Modifiers

b) Non-Access Modifiers
--------------------------
a) Access Modifiers
We use access modifiers to define access control for classes, methods and variables.

Four Access Modifiers

i) private
The private access modifier is accessible only within class.

Ex:

private int a =100;

2) default
If we don't specify any modifier then it is treated as default, this can be accessible only within package.

class Sample{
.
.
}

3) protected
The protected access modifier is accessible within package, outside of the package but through Inheritance only.

protected class Sample{
.
.
}

4) public
public access modifier is accessible everywhere.

public class Sample {
.
.
}
---------------------------------------------------
Modifier
Within Class
Within Package
Outside of the Package
(By Sub Class)
Outside of the Package
private
Y
N
N
N
default
Y
Y
N
N
protected
Y
Y
Y
N
public
Y
Y
Y
Y
 

b) Non Access Modifiers
1) static
static modifier is used create classes, methods and variables.

Ex:

static int a =10;

static void int add(){
.
.
}

2) final
final modifier for finalizing of classes, methods and variables.

Ex:
final int a =100;
.
.
.
a=200; //Error
---------------
int a =100;
.
.
.
.
a =200;
------------------
3) abstract
abstract modifier is to create abstract classes, abstract methods

ex:

abstract class Sample{
.
.
}
-------------------------------
ii) Java Variables
1) What is Variable?
A named memory location to store the temporary data within a program.

Two types of memories in Computer environment

a) Primary memory (RAM)

b) Secondary memory (HDD, DVD, USB drive etc...)
----------------------------
2) Declaration of Variables
Java supports Explicit declaration of Variables.

Syntax and Examples:

dataType variableName;

int a;
-------------
dataType variablename=value;

int b=20;
---------------
dataType variable1, Variable2, variable3;

int a, b, c;
-----------------
dataType variable1=value; variable2=value; varible3=value;

int a=10; b=20; c=30;
------------------------------------
3) Assign values to variables
a) Initialization

b) Reading

Ex:

int a=100; //Initialization

int a=10;
int b;
b=a; //Reading
---------------------------------
4) Variable Naming Restrictions
> Java variables are case sensitive,

> Java variable name should start with a letter or $ or _

Ex:

myvar(Correct)
MYVAR
$myvar
_myvar
myvar_1
--------------
1myvar(Incorrect)
*myvar
----------------
> Variable names should not match with Java keywords/Reserved words.

> Must be unique in the scope of declaration.

> Variable names Must exceed 255 characters.
-------------------------------------------

5) Types of Variables
Three types of variables in Java
a) Local variable(Local variable is declared in methods or blocks.)

b) Instance variable(Instance variables are declared in a class but outside of a method or any block)

c) Class/Static variableA Variable that is declared as static, It cannot be local.
----------------------------------
Example:

package xyza;

public class VariablesExample {
//a Variable is a Class/Static variable
static int a =100;

//mysalary variable is a Local variable.
public int salary(){
    int mysalary =10000+2000+1500;
    mysalary=mysalary + a;
    return mysalary;
}

public static void main (String[]args){
//Instance variable
int b =200;
System.out.println(a);//100
System.out.println(b); //200   
       
VariablesExample obj= new VariablesExample();   
System.out.println(obj.salary());
// i is a Local Variable   
for (int i=1; i<=5; i++){
    System.out.println(i);
    System.out.println(a);
    System.out.println(b);
}
}
}
----------------------------------
iii) Java Operators
Important Categories of Operators

a) Arithmetic Operators

b) Relational Operators

c) Assignment Operators

d) Logical Operators
-------------------------------
a) Arithmetic Operators
1) Addition + (for Addition, String concatenation)

2) Subtraction - (for Subtraction, Negation)

3) Multiplication *

4) Division /

5) Modules %

6) Increment ++

7) Decrement --
---------------------------
Example:

public class OperatorsExample {
    public static void main (String [] args){
        int a =10, b=5;
        String c ="Selenium", d= "Testing";

System.out.println("Addition of a, b is: "+ (a+b));//Addition of a, b is: 15
System.out.println("Subtraction of a, b is: "+ (a-b));       
System.out.println("Multiplication of a, b is: "+ (a*b));   
System.out.println("Addition of a, b is: "+ (a/b));   
System.out.println("Addition of a, b is: "+ (a%b));

b=10;
a = ++b;
System.out.println(a);//11

b=10;
a = --b;
System.out.println(a);//9
}
}
---------------------------------------
b) Relational Operators
1) ==

2) !=

3) >

4) >=

5) <

6) <=
----------------------------------
Note: Relational Operators return Boolean / Logical result

Example:

public class OperatorsExample {
    public static void main (String [] args){
        int a =10, b=20;
        System.out.println((a>b));//false
        System.out.println((a>=b));//false
        System.out.println((a==b));//false
       
        System.out.println((a<b));//true
        System.out.println((a<=b));//true
        System.out.println((a!=b));//true
}
}
------------------------------------------------
d) Logical Operators
1) Logical Not Operator  !

2) Logical And Operator &&

3) Logical Or Operators ||

Result Criteria

Not operator
--------------
Operand1    Operand2    Result
--------------------------------------
true               true         false
true               false        true
false              true         true
false              false        true
--------------------------------------
And operator
--------------
Operand1    Operand2    Result
--------------------------------------
true             true            true
true             false           false
false            true            false
false            false           false
--------------------------------------
Or Operator

Operand1    Operand2    Result
--------------------------------------
true             true             true
true             false            true
false            true             true
false            false            false
--------------------------------------
Example:

public class OperatorsExample {
    public static void main (String [] args){
        boolean a =true, b=false;
        System.out.println(!(a && b));//true
        System.out.println((a && b));//false
        System.out.println((a || b));//true
    }       
}
--------------------------------------
public class OperatorsExample {
    public static void main (String [] args){
        int a =1000, b=500, c=7000;

if ((a>b) && (a>c)){
    System.out.println("A is a Big Number");
}
else{
    System.out.println("A is Not a Big Number");   
}
}       
}
--------------------------------------
c) Assignment Operators
1) Assignment Operator

=

a=10;

2) Add and Assign +=

3) Subtract and assign

4) Multiple and assign
-------------------------------
Example:
public class OperatorsExample {
    public static void main (String [] args){
        int a =10;

System.out.println(a);//10
a+=10;
System.out.println(a);//20

a-=10;
System.out.println(a);//10

a*=10;
System.out.println(a);//100
}       
}
-----------------------------------------------------------
Bitwise Operators
> Java defines several bitwise operators, which can be applied to the integer types, Bitwise operator works
   on bits and performs bit-by-bit operation.

i) The bitwise & operator performs a bitwise AND operation.

ii) The bitwise ^ operator performs a bitwise exclusive OR operation.

iii) The bitwise | operator performs a bitwise XOR operation.

Java Program Structure and Java Syntax


Java Program Structure and Java Syntax

i) Java Program Structure

ii) A Sample Java Program

iii) Comments in Java

iv) Java Data Types
-----------------------------------------
Java Environment Setup
 

> Download Java (JDK) Software and Install

> Set Environment Variable (Path variable)

> Download Eclipse IDE and Extract.
--------------------------
Create Java project
    > Create Java Package
        Create Java Class /Program
-----------------------------------------
i) Java Program Structure
 

1) Documentation Section

2) Package declaration Statement

Ex: package xyza;

3) Import Statements

We import built in and User defined libraries using import keyword

Ex:

import java.io.Console;
import java.lang.*;

import - It is a Java keyword to import Libraries.

java -Project

io -Package

Console - Class

lang.*; - import all classes from lang package.
--------------------------------------
4) Class declaration Statement

public class Sample {

}

public - Access Modifier

class - Java keyword to declare a class

Sample - it is the Class name (You can use any meaningful name)
----------------------------------------------
5) main Method (Java Program execution starts from main method)
(* It is the mandatory statement in every Java program)

public static void main (String [] args) {
}

public - Access Modifier

static - Non-Access Modifier (use main method without invoking any object)

void - Returns nothing

main- method name
-----------------------------------
6) Declarations

We can Declare Variables and Constants.

Other Statements

System.out.println("Hello Selenium");

System - Class (Pre-defined)

out - Object

println - method

"Hello Selenium" - Message
--------------------------------
7) Code blocks

Condition blocks

Loop blocks

Method blocks (method declaration before the main method, but we access methods after main method)
etc...
-------------------------------------
> Every normal statement/step ends with semi colon

> Every code block enclosed with {}
-----------------------------------------
ii) A Sample Java Program
 

//Documentation

package xyza;

import java.io.Console;
import java.lang.*;

public class Sample {

//Create a Method(User defined)
public int multiply(int a, int b, int c){
int result = a * b * c;
return result;
}

public static void main (String [] args){
// This is a sample Program

int a = 10, b, c; //Variables Declaration   
b = 20; c = 30; //Initialization

final int money =100;//Constant Declaration

System.out.println("Addition of a, b is " + (a + b));//Addition of a, b is 30
System.out.println(money);//100
System.out.println(c);//30

//Condition Block
if (a > b){
System.out.println("A is a Big Number");
}
else
{
System.out.println("B is a Big Nuber");
}

//Loop block

for (int d=1; d <=10; d++){
    System.out.println(d);
}
//Create Object and access Methods
Sample obj = new Sample();
int x = obj.multiply(10, 25, 50);
System.out.println(x);
}
}
-----------------------------------------
iii) Comments in Java
 

Comments are English words used for Code documentation.

Purpose of Comments

    a) To make the code Readable

    b) To make the code disable from execution
------------------------
Comments Syntax in Java

Use // for Single line comment

Use /* ......
...........
..............
*/ for multiple lines comment

Example:
package xyza;

public class Sample2 {

public static void main (String [] args){
//This is a Sample Program
int a, b, c; //Declaration of variables
a=10; b=20;c=30;
       
/*if (a > b){
System.out.println("A is a Big Number");
}
else {
System.out.println("B is a Big Number");   
}*/

System.out.println(c);
}
}
------------------------------------
Usage of Comments in Test Automation

a) To write Test Case header

b) To write Method header

c) To explain complex logic etc...
-----------------------------------------
iv) Java Data Types
 

Data Type is a classification of the type of data that variable or Constant or object can hold in computer programming.

Ex: character, integer, float, boolean etc...

Java Supports Explicit Declaration of Data Types.
(we need to specify the data type before declaring the a Variable or constant etc....)

Syntax:

dataType variableName;

dataType variableName =value;

dataType variable1Name, variable2Name, variable3Name;

Example:

int a;

char b ='A';

int a, b, c;
-----------------------------
Two Types of data Types in Java

a) Primitive Data Types

b) Non-primitive Data Types / Reference Data Types
--------------------------------
a) Primitive Data Types (8 data types)

i) Integer Types
----------------
1) byte (8 bits)

byte a =10;

2) short (16 bits)

short a =10000;

3) integer(32 bits)

int a = 100000;

4) long (64 bits)

long a =100000000000000;
------------------------
ii) Relational types (Numbers with decimal places)

5) float (32 bits)

float a = 1.23;

6) double (64 bits)

double a =123.345654322;
-------------------------------
iii) Characters

7) character

char a ='Z'
----------------------------
iv) Conditional

8) Boolean

boolean a = true;
------------------------------
b) Non-primitive Data Types / Reference Data Types

Non-primitive or Reference data types in Java are Objects and Arrays.

ex:

Button a = new Button("OK")
---------------------------------------------------