You are on page 1of 290

Syllabus for Automation :

Core Java
Basic terminologies

Classes

Methods

Variable

Constructor

Loops

Practice of some programs:

OOPs concept:

1. Inheritance 2. Polymorphism 3. Encapsulation 4. Abstraction 5. Interface 6. Abstract

Control statement(If –else, else if, switch case etc)

Exception handling

Array

String Class

Collections

Selenium
Concept of Automation setup

Basic commands of selenium

Handling of different elements

TestNG

Framework development

Git repository

Jenkins
Automation Testing:
Definition:
Process through which quality of product can be
guaranteed by using code to perform the actions
automatically over the application without intervention of
any user.

Need and advantages of Automation:


1. Repetitive task which should be perform at all the
stages requires automation.
2. To ensure the quality within less amount of time.
3. To reduce human efforts and error caused by individual.
4. To ensure the quality on different browser at a same
time.
5. Operating system based testing can also be achieved.
6. Report which tells us about the complete execution of
the code.
How do we decide the platform for Automation:
Platform – Eclipse IDE(Integrated development
environment, widely used almost in all organization)
Programming language- - Java

Feature:
1. Simple
2. Object oriented language
3. Secure
4. Portable
5. Multithreaded
6. Garbage collector.
7. Slogan of java – “Java is every where” because Write
once and run any where.
For Webbase application the most popular and easy to
use open source tool is Selenium.

Java + Selenium === Automation Tool

In 1991 java was developed by Sun microsystems.


Flavours of java:
1. Java SE(Core java) Standard edition. -- Basic
2. Java EE(Advance java) Enterprise edition.—Sever/
Backend related application
3. Java ME(Micro Edition) –Mobile based application
Architecture of Java:
Java has two processes, compilation, and
interpretation. The Java Compiler converts the
code present in Java into byte codes. The Java
Virtual Machine (JVM) converts the byte codes
into machine code which the machine executes
directly.

The JRE builds a runtime environment where you


can execute the Java programs. It takes the Java
code and combines the same with the required
libraries

Interpreter translates just one statement of the


program at a time into machine code. Compiler
scans the entire program and translates the whole
of it into machine code at once. An interpreter
takes very less time to analyze the source code. ...
A compiler take more time.

To download java:

https://www.oracle.com/in/java/technologies/javase/javase-jdk8-downloads.html

To download eclipse oxygen:

https://www.eclipse.org/downloads/packages/release/oxygen

click on Eclipse 3A

and select Eclipse IDE for Java Developer


To configure java in the system :

Go to c:/Programfiles/Java

Go to jdk specific folder

Go to bin folder

Copy the entire path

Like C:\Program Files\Java\jdk1.8.0_241\bin

Right click to this pc and click on properties


Go to advance system settings

Click on Environment variable


Go to new (Windows 10) and paste the copied path

Eclipse setup:

1. Extract the content of eclipse which was downloaded.


2. Click on the eclipse icon.

3. Click on File and say new and select java project

To create package

Command to check the version of java

java –version
Class :
Class is a plan through which we come to know what are the different logic we are
having in it.

Collection of objects is called a class.

Example:

package basic;

public class JavaBasicProgram {

public static void main(String[] args) {

System.out.println("Hello this is my first program-1");


System.out.println("Hello this is my first program-2");
System.out.println("Hello this is my first program-3");
System.out.println("Hello this is my first program-4");
System.out.println("hdjaajks");
}
}

Shortcuts:

To execute the code:

First way: Click on green icon

Second way: Right click on class and select Run as java


application

Third way: ctrl+f11


To comment the code:

Ctrl+shift+c
Java is strongly typed language means every single element for
example a variable has some type.
Datatypes in java:
A data type provides a set of values from which an expression (i.e.
variable, function, etc.) may take its values.
1. Byte

Range is +127 to -128

Example:

// byte = 1 byte or 8 bits maximum value = +127 and min value = -128

byte bytevarname = 127;


byte bb = -128;

//short = 2 bytes or 16 bits maximum value = 32767 and min value = -


32768
short sh = 32767;
short shh= -32768;

// int = 4 bytes or 32 bits maximum value = 2147483647 and min value = -


2147483648

int i = 2147483647;

// long = 8 bytes or 64 bits maximum value = 2^63-1 to and min


value = -2^63
long l = 64654654645l;

Note: The most common and preferred data type in numeric is integer.

Floating data type

// float = 4 bytes range = -3.4* 10^38 to 3.4 * 10^38

float f = 1.26565656f;
//double = 8 bytes range = -3.4*10^308 to 3.4*10^308

double d = 2121215.3432476234782364723462378;

boolean data type has only 2 options either true or false

boolean b = true;
boolean bbs = false;

//char = 2 bytes

char ch = 'a';
char cc = '$';

Operations on data type:

Example

int i;//declaration of variable

i=100;// initialization

int j = 20;// initialization and declaration

int k = i/j;

System.out.println("k value is ");

System.out.println(k);

System.out.println("K value is :"+k);

double d = 56.665;
double dd = 12.56;

double ee = d+dd;

System.out.println(ee);

Output:

k value is
5
K value is :5
69.225

Objects:
Definition of object:
Combination of state i.e. variables and behavior (Which can be achieved through methods) is
called an Object.

For example: Physical representation of memory over the system through which are performing
a task.

// Creation of object
//syntax-- Classname reference variable name = new Class name ();

Methods in Java:
Methods are nothing but a set of code which represents a logic that can
be call numerous times whenever require.
Defination: To represent logic or behavior in java we require a method

Types of method:

1. Regular method

2. main Method
Regular method:

Types of regular method:

a. Static method

b. Non-static method

1. Regular methods:

a. static method:
These are class level methods that is they got loaded at the time of class loading.

To call the static method in the same class where it was defined, we need to call it directly by
writing name only.
Example 2:

package methodsdiscussion;

public class Test {

//Object

//behavior-- > to print ---> method

// properties --> quality---> variable

//Static method

Example:

public class Test {

public static void myFirstMethod()


{
System.out.println("one");
System.out.println("two");
System.out.println("three");
System.out.println("four");
System.out.println("five");

public static void addition()


{
int i = 10;
int y = 20;
int z = i+y;
System.out.println(z);

}
public static void main(String[] args) {
myFirstMethod();//calling of a method
addition();

}
}

Example 2: If static method got defined in other class:

public class Test2 {

public static void m2()


{
System.out.println("Test2 class m2 method is running");
}
}

Public class Test{

public static void main(String[] args) {

Test2.m2();// If we want to call a static method from other class then


we have to call it by Classname.method nam

Note: Ways to call static method:

1. By direct name of method provided method is in the same class

2. By Classname.method name

3. By object reference variable but it is not recommended.

For example:
Test t = new Test();

t.m3();// m3 is a static method

b. Nonstatic method or instance method:


These method are object dependent methods which will be called only after
creating an object. Memory allocation will be done once non static method
gets call. Also de-allocation of memory takes place after the execution of
method.

Example 1 :

With in the same class

public class Test {

public void m3()


{
System.out.println("This is non static method");

public static void main(String[] args) {

Test t = new Test(); // creating an object

t.m3();// to call a non static method

Output: This is non static method

Example 2 non- static method which is outside of class


public class Test {
public static void main(String[] args) {

Test2 t2 = new Test2();

t2.m5();

public class Test2 {

public static void m2()


{
System.out.println("Test2 class m2 method is running");
}

public void m5()


{
System.out.println("Test2 class m5 non static method is
running");
}

Output:

This is non static method


Test2 class m5 non static method is running
Process of executing a program:
Test.java

1. start jvm

2. jvm create the main thread.

3. Locate Test.class file

4. Load Test.class file --- static method and variable memory allocation

5. execute main method --non static method loading by creating an object

6. Unload Test.class file. --static method and variable memory deallocation

7. JVM Shutdown.

Difference between Static and non static method:


Sr. no Static method Non static method

1 Static methods are class level Non Static methods are object level methods
methods

2. It can be accessible directly inside the It can be accessible only after creation of
main method (if it is defined in the object.
same class) or by classname.method
name or by referencevariable.method
name.

3. Memory allocation is happening at the Memory allocation is happening once the


time of loading a class and de- method gets call and once the execution gets
allocation at the time of unload of completed it gets de-allocate.
class.

4 It is recommended only when we are It is recommended when we are not sure to


sure of its usage. execute all of them.

5 Syntax – public static void name of Syntax- public void nameofmethod


method
package methodsdiscussion;

public class Test {

public static void myFirstMethod()


{
System.out.println("one");
System.out.println("two");
System.out.println("three");
System.out.println("four");
System.out.println("five");

public static void addition()


{
int i = 10;
int y = 20;
int z = i+y;

System.out.println(z);

//Nonstatic method or instance method


//syntax: public void nameofmethod()
// {
//
// }
public void m3()
{
System.out.println("This is non static method");

}
public static void m2()
{
myFirstMethod();
}

public void m4()


{
myFirstMethod();
}

public static void main(String[] args) {


// myFirstMethod();//calling of a method
// Test.myFirstMethod();
// Test2.m2();

// Creation of object
//syntax-- Classname reference variable name = new Class name ();
Test t = new Test();

t.m3();// to call a non static method

Test2 t2 = new Test2();

t2.m5();

t.m2();// not recommended


// addition();
//
// Test2.m2();// If we want to call a static method from other
class then we have to call it by Classname.method name
//

Calling of methods in either types of


methods:

1. Calling of static method in another static method:


We can call directly(by name of method) in another static method provided it in the
same class or by Classname.method name(if in another class) or by creating an
object(not recommended)

public static void m2()


{
myFirstMethod();
Test.myFirstMethod();
Test ttt = new Test();
ttt.myFirstMethod();

2. Calling of static method in non static method:


We can call directly(by name of method) in another non static method provided it in the
same class or by Classname.method name(if in another class) or by creating an object.
(not recommended).

public void m4()


{

myFirstMethod();
Test.myFirstMethod();

Test tt = new Test();


tt.myFirstMethod();

3. Calling of non static method in static method:


By creating an object of the class which contains that particular non static method.

Example:

public static void m2()


{
Test ttt = new Test();
ttt.m5();
ttt.m3();
ttt.m4();

4. Calling of non static method in non- static


method:
By calling directly name of method in non static method provided it is in the
same class. But if another non static method is available outside the class
then we have to create an object.
public void m8()
{
m4();
Test2 t = new Test2();
t.m5OfTest2();

Main Method:
A method which gets execute by jvm once
programmer calls the entity in a particular sequence.
Main method can be called like other static methods.
For example:
public class Test {
public static void main(String[] args) {

Test2.main(args);

public class Test2 {

public static void main(String[] args)


{
System.out.println("main of Test2");
}
}

Types of Variables
Based on the location of defining a variable they are categorize in to 3 types:

1. Static variable

2. non static variable

3. local variable

1. static variable:
a. These are class level variable which define only at class level but not in any other
methods, but they can be accessible throughout the class.

b. syntax: static datatype variable_name = value;

or

static datatype variable_name;

c. Static variable can be access through :


i. directly by name(If it is in the same class)

ii. By Classname.Variable_name.

iii. By creating object but it is not recommended

d. Static variable will be created at the time of class loading and destroy at the time of
unloading hence scope of static variable is exactly same as the scope of .class file.

e. If we don’t assign the value to the variable then it attains default values and those
default values are:

//default values
//byte = 0;
//short = 0;
//int == 0;
//long = 0;
//float = 0.0;
//double = 0.0
//boolean= false
//char = ' ';

example:

public static void myFirstMethod()


{

// accessing static variable


System.out.println(i);
System.out.println(Test.i);

// accessing variable by using object but it is not recommended


Test t = new Test();
System.out.println(t.i);

System.out.println("The value of i variable is :"+i);

}
package methodsdiscussion;

public class Test {

static int i = 50;

//accessing static variable in static method

public static void myFirstMethod()


{
System.out.println(i);

System.out.println("The value of i variable is :"+i);

//accessing static variable in non static method


public void m1()
{
System.out.println(i);
System.out.println("Value of static variable access by non static
method :"+i);
}

//accessing static variable in main method


public static void main(String[] args) {

myFirstMethod();

System.out.println(i);
int y= i+2;

System.out.println("Y value is :"+y);

Test t = new Test();


t.m1();
}

}
Output:

50
The value of i variable is :50
50
Y value is :52
50
Value of static variable access by non static method :50

2. Non static variable or instance variable:

a. These are the variable which gets define at the class level but they can
access through only by object in case of static method.

b. Syntax— datatype variable_name = value;

or

datatype variable_name;

c. If we don’t assign any value then it automatically attains default value.

d. non static variable value gets differ from object to object.

e. Non static variable will get created at the time of object creation and
destroy at the time of object destruction hence scope of non static variable
is same as object scope.

f. if we wants to call non static variable in non static method then it will get
call directly without creating an object.
Example 1:

public class Test2 {

int i = 50;
//or
int j;

public static void main(String[] args) {


Test2 t = new Test2();
System.out.println("before changing the value of i from t
variable is :"+t.i);
t.i= 60;

System.out.println("after changing the value of i from t variable


is :"+t.i);

Test2 u = new Test2();

System.out.println("i value from u reference variable before


change is :"+u.i);
u.i = 10;
System.out.println("i value from u reference variable after
change is :"+u.i);

}Output:

before changing the value of i from t variable is :50


after changing the value of i from t variable is :60
i value from u reference variable before change is :50
i value from u reference variable after change is :10

Example 2- using method accessing the values of nonstatic variable


public class Test2 {

int i = 50;
//or
int j;

public void m1()


{

System.out.println(i);

public static void main(String[] args) {


Test2 t = new Test2();
System.out.println("before changing the value of i from t
variable is :"+t.i);
t.i= 60;
t.m1();//60

System.out.println("after changing the value of i from t variable


is :"+t.i);

Test2 u = new Test2();

System.out.println("i value from u reference variable before


change is :"+u.i);
u.i = 10;
u.m1();//10
System.out.println("i value from u reference variable after
change is :"+u.i);

}
Example of static variable with respect to object:

int i = 50;
//or
int j;

static int k = 20;

public void m1()


{

System.out.println(i);

public static void main(String[] args) {


Test2 t = new Test2();
System.out.println("the value of k without using object " +k);

System.out.println("k value using t reference variable :"+t.k);

k = 30;

System.out.println("k value after changing without using object


" +k);

System.out.println("k value after changing using t reference


variable :"+t.k);

Test2 u = new Test2();

System.out.println("k value using u reference variable :"+u.k);

Test2 v = new Test2();


System.out.println("k value using v reference variable :"+v.k);

Output:
the value of k without using object 20
k value using t reference variable :20
k value after changing without using object 30
k value after changing using t reference variable :30
k value using u reference variable :30
k value using v reference variable :30

3.Local Variable:
The variables which are defined within the curley brace of methods or
constructor and the scope of that variable would be within the curley
braces.

a. JVM doesn’t provide default values if the value has not been initialized
we will get an error if we try to use that variable without providing value.

b. If the name of local variable same as non static variable then for
accessing non static variable we have to use this keyword.

d. If the name of the local variable is same as static variable the for
accessing static variable we have to use class name.variable name.

public void m1()


{
int i; //here we have declare but not initialized

System.out.println(i);// error due to not initialized

}
Example for
Use of this keyword in java

To access non static variable in non static area or method we


can use this keyword. “this” keyword is not applicable to static
area or method.
Example: public class Test2 {

int i = 50;
//or
int j;

static int k = 20;

public void m1()


{
int i;
i =10;

// for accessing non static variable


System.out.println(this.i); // 50

//for accessing local variable


System.out.println(i); //10

public static void main(String[] args) {

Test2 t = new Test2();


t.m1();

Differences between static non static and local variable:

Sr no Static variable Non Static Local Variable


They are defined at the
method level or within
1 They are defined at class level They are defined at class level the curley braces.
Scope is upto the
boundary of the curley
2 Scope is throughout the class Scope is throughout the object. braces.
Memory allocation is done at Memory allocation at the time of creation Memory allocation at
3 the time of class loading. of object the time method call.
this keyword is applicable and we are able
this keyword is not applicable to to access the non static variable with in this key word is not
4 the static variable the non static area. applicable.
JVM doesn’t provide
any support for default
value programmer has
to initialize before
JVM provides default value if the JVM provides default value if the value using.
5 value has not been initialized. has not been initialized.
Value of static variable doesn’t
get change from object to
object. Here we share the value
of static variable with every Value of non static variable gets change This is not applicable.
6. object. from object to object.

If else use with local variable:


public static void m2()
{
int i = 10;
int k = 5;
Test2 t= new Test2();
System.out.println(t.i);

if(i<k)
{
int l = 10;
System.out.println(l);

}
else
{
int m = 20;

Methods with argument and return type.

package Utility;

public class Test {


//method with argument and no return
public void m1(int a, int b)
{

int c = a+b;
System.out.println(c);
}

//method without argument and no return

public void m2()


{

int c = 0;
System.out.println(c);
}
//method without argument with return
public boolean m3()
{

return false;
}
//method with return type and no argument
public int m4()
{
int a = 1;
int b = 2;
int c = a+b;

return c;

//method with return type and argument

public int m5(boolean b, int c, double d)


{

b = true;
c= 63;

return 50;

public static void main(String[] args) {


Test t = new Test();
t.m1(10, 20);
boolean r = t.m3();

System.out.println("r value is :"+r);

int d = t.m4();
int e = d+5;
System.out.println("e value is :"+e);
t.m5(true, 0, 83.23);

}
Output:

30
r value is :false
e value is :8

Example 2:

package Utility;

public class Test {


// method with argument and no return
public static void m1(int a, int b) {

// method without argument and no return

public void m2() {

int c = 0;
System.out.println(c);
}

// method without argument with return


public boolean m3() {
return false;
}

// method with return type and no argument


public int m4() {
int a = 1;
int b = 2;
int c = a + b;

return c;

// method with return type and argument

public int m5(boolean b, int c, double d) {

b = true;
c = 8;

return 50;

public static void main(String[] args) {

Test t = new Test();

boolean r = t.m3();

System.out.println("r value is :" + r);

int f= t.m4()+3;

System.out.println(f);//6

System.out.println(t.m4()+3);//6
}
}
Constructors:
Definition:

A special method which get execute at object creation.

Types of constructors:-
1. Default constructor

If you do not implement any constructor in your class, Java compiler inserts a
default constructor into your code on your behalf.

2. no-arg constructor

Constructor with no arguments is known as no-arg constructor.

3. Parameterized constructor

Constructor with arguments(or you can say parameters) is known as


Parameterized constructor.

Rules:

 Name of constructor and class name must be same.

 Constructor can accept the arguments.

 Constructor can’t have return type.

 A class can have multiple constructor.

 Constructor can call another constructor by using ‘this’ keyword but


we can call another constructor only in line 1 of that constructor.
Usage:

 Constructor is one which execute at the time of object creation.

 To initialize the data member.


Use 1:

public ConstructorBasics()
{
System.out.println("constructor is running");
}

public static void main(String[] args) {


ConstructorBasics cb = new ConstructorBasics();

Output: Constructor is running

Usage 2( to initialize data members i.e variable):

package Utility;

public class ConstructorBasics {

// to create constructor

//Syntax -- public name_of_class()


// {
//
// }
int m;
int s;
int e;
public ConstructorBasics(int m, int s, int e)
{
this.m = m;
this.s = s;
this.e = e;
}

// or
// public ConstructorBasics(int mm, int ss, int ee)
// {
// m = mm;
// s = ss;
// e = ee;
// }

public static void main(String[] args) {


ConstructorBasics cb1 = new ConstructorBasics(10, 20, 30);
ConstructorBasics cb2 = new ConstructorBasics(40, 50, 60);

ConstructorBasics cb3 = new ConstructorBasics(7, 2, 0);


ConstructorBasics cb4 = new ConstructorBasics(4, 5, 6);

ConstructorBasics cb5 = new ConstructorBasics(10, 20, 30);


ConstructorBasics cb6 = new ConstructorBasics(40, 50, 60);

ConstructorBasics cb7 = new ConstructorBasics(10, 20, 30);


ConstructorBasics cb8 = new ConstructorBasics(40, 50, 60);

ConstructorBasics cb9 = new ConstructorBasics(10, 20, 30);


ConstructorBasics cb10 = new ConstructorBasics(40, 50, 60);

System.out.println(cb7.m);

}
Output: 10

Example 3:multiple constructor in single class:


package Utility;

public class ConstructorBasics {

// to create constructor
// Syntax -- public name_of_class()
// {
//
// }
int m;
int s;
int e;

public ConstructorBasics(int m, int s, int e) {


System.out.println("three argument constructor");
}

public ConstructorBasics(int m) {
System.out.println("one argument constructor");
}

public ConstructorBasics(int m, boolean b) {


System.out.println("two argument constructor");
}

// or
// public ConstructorBasics(int mm, int ss, int ee)
// {
// m = mm;
// s = ss;
// e = ee;
// }

public static void main(String[] args) {


ConstructorBasics cb1 = new ConstructorBasics(10);
ConstructorBasics cb2 = new ConstructorBasics(40, 50, 60);

ConstructorBasics cb3 = new ConstructorBasics(7, false);

}
Output:
one argument constructor
three argument constructor
two argument constructor

Example 3 : Calling of constructor in another one

package Utility;

public class ConstructorBasics {

// to create constructor

// Syntax -- public name_of_class()


// {
//
// }
int m;
int s;
int e;

public ConstructorBasics(int m, int s, int e) {


System.out.println("three argument constructor");
}

public ConstructorBasics(int m) {
System.out.println("one argument constructor");
}

public ConstructorBasics(int m, boolean b) {


System.out.println("two argument constructor");
}

public ConstructorBasics()
{
this(14);
System.out.println("zero argument constructor");
}

// or
// public ConstructorBasics(int mm, int ss, int ee)
// {
// m = mm;
// s = ss;
// e = ee;
// }

public static void main(String[] args) {

ConstructorBasics cb = new ConstructorBasics();

Example 4:

Calling of one constructor to another one

package Utility;

public class ConstructorBasics {

// to create constructor

// Syntax -- public name_of_class()


// {
//
// }
int m;
int s;
int e;

public ConstructorBasics(int m, int s, int e) {


System.out.println("three argument constructor");
}

public ConstructorBasics(int m) {
this(10, true);
System.out.println("one argument constructor");
}

public ConstructorBasics(int m, boolean b) {


this(10, 20, 30);
System.out.println("two argument constructor");
}

public ConstructorBasics()
{
this(14);

System.out.println("zero argument constructor");

// or
// public ConstructorBasics(int mm, int ss, int ee)
// {
// m = mm;
// s = ss;
// e = ee;
// }
public static int m5()
{
return 66565656}
public static void main(String[] args) {

ConstructorBasics cb = new ConstructorBasics();

}
}
Output is :

three argument constructor


two argument constructor
one argument constructor
zero argument constructor

Operators :

int x
int y
initial value final value
Sr. no Expression of x value of y of x
1 y = ++x 10 11 11
2 y= x++ 10 10 11
3 y= --x 10 9 9
4 y = x-- 10 10 9

Example:
public static void main(String[] args) {
int x = 10;
int y = ++x;
char c = 'a';
c++;
System.out.println(c);
System.out.println("x value is :"+x +" y value is :"+y);

Output:

x value is :11 y value is :11

//Comparasion operator:

//> greater than operator

if(w>z)
{
System.out.println("if block is running");
}

else
{
System.out.println("else block is running");
}

// greater than or equal to operator


if(y>=x)
{
System.out.println("if block is running");
}

else
{
System.out.println("else block is running");
}

if (x<y)

if (x<=y)
{

Output:

a
b
x value is :11 y value is :11
else block is running
if block is running

If –else
 This is a control statement which execute if body once the condition
is true else it execute ‘else’ body.

 Curley braces are optional in if-else provided we have only one line
statement in it.

 Without curley braces the statement should not be declarative i.e


initializing a local variable.

if (x>y)
System.out.println("if is running");
else
System.out.println("else is running");

// equal to operator:
if(x==y)
{
System.out.println("x and y values are equal");

// not equal operator:

if (x!=y)
{
System.out.println("x and y are not equal");

if(!(x>y))
{
System.out.println("last if block is running");
}

if((x>y)&&(y==12))
{
System.out.println("Logical if block is running");

if((x>y)||(y==0))
{
System.out.println("Logical OR block is running");

Loops:
1 loop :
//while loop
//syntax
// while(boolean condition)
// {
// Actions;
// }

int x =0;

while(x<5)
{
System.out.println("hello");
x++;

hello
hello
hello
hello
hello
Note: - Curley braces are optional but we can have only one statement which should not be
declarative.

//2 loop--
do-while loop
// Syntax:
// do
// {
// //actions
// }
// while(x!=3);
do
{
System.out.println("do while loop is running");
x++;
}
while(x<5);

}
Note: if we wants to execute a loop atleast once then we should go for do-
while loop. In which do block will get execute irrespective of while condition.

Modulus operator(%): This operator gives the remainder after the division
of two numbers

Example:

int x =11;
int y = 2;

int z= x/y;

int w = x%y;
System.out.println(z);
System.out.println(w);

5
1

//3 for loop:


// syntax:
//1 //2, 5, 8
//4, 7
// for(intitialization section; conditional section; increment/decrement
section)

//{ 3, 6, 9
// Actions
//}

for(int i=0; i<=5; i++)


{
System.out.println("For loop");

}
Output:

For loop
For loop
For loop
For loop
For loop
For loop

Example 2:

for(int i=0; i<=5; i++)


{

System.out.println("The value of i is :"+i);


}
Output:

The value of i is :0
The value of i is :1
The value of i is :2
The value of i is :3
The value of i is :4
The value of i is :5

Example 3:
for(System.out.println("first statement from for loop"); i<=5; i++)
{

System.out.println("The value of i is :"+i);


}

Output:

first statement from for loop


The value of i is :0
The value of i is :1
The value of i is :2
The value of i is :3
The value of i is :4
The value of i is :5
Patterns logic
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
j
Rows = i 1 2 3 4 5
Column =j 1 *        
2 * *      
initial value of i= 1 i 3 * * *    
4 * * * *  
5 * * * * *

Step 2 Step 3
  i j i j
  1 1 1 j<=1
  2 1, 2 2 j<=2
  3 1, 2 ,3 3 j<=3
  4 1, 2, 3, 4 4 j<=4
  5 1, 2, 3, 4, 5 5 j<=5

Step 4
j<=i

public static void main(String[] args) {


for(int i= 1; i<=5; i++)
{

for(int j = 1; j<=5; j++)


{
if(j<=i)
{
System.out.print("*");
}

else
{
System.out.print(" ");
}

}
System.out.println();
}

Output:

*
**
***
****
*****

Example 2:

Step 2 * * * * *
  i j * * * *  
  5 1 * * *    
  4 1, 2 * *      
  3 1, 2 ,3 *        
  2 1, 2, 3, 4
  1 1, 2, 3, 4, 5

Step 3
1 j<=5
2 j<=4
3 j<=3
4 j<=2
5 j<=1

Step 4
j<=(6-i)

public static void main(String[] args) {


for(int i= 1; i<=5; i++)
{

for(int j = 1; j<=5; j++)


{
if(j<=(6-i))
{
System.out.print("*");
}

else
{
System.out.print(" ");
}

}
System.out.println();
}

}
Output:

*****
****
***
**
*

Ex 2

public class ReverseNumber {

public static void main(String[] args) {

int num = 1234, reversed = 0;

while(num != 0) {

=tnu
gm
in
dti i%10;

sede
svrd=r
evr;*1t0+d
gii

num=num/
10;

System.out.println("Reversed Number: " + reversed);

Output

Reversed Number: 4321


Break key word in java:

It is used to break a particular loop and make the control out of the loop. The loop can also be
defined by label.

//break key word in java


for(int i = 0; i<=5; i++)

if(i==3)

break;

System.out.println("i value is "+i);

// labelled for loop with break key word

outerforloop: for (int i = 0; i < 5; i++) {

for (int j = 0; j < 5; j++) {

if (j == 2)

break outerforloop;
}

Continue keyword in java:


It is used to jump to the next iteration whenever continue keyword gets execute.

for(int i = 0; i<=5; i++)

if(i==3)

continue;

System.out.println("i value is "+i);

Output:

i value is 0

i value is 1

i value is 2

i value is 4

i value is 5
Example 3:

for(int i=0; i<10; i++)

if(i%2 == 0)

continue;

System.out.println(i);

Output:

Reverse a number logic:

int no = 7427374;
int rem;
int rev = 0;

while (no != 0) {
rem = no % 10;
rev = rev * 10 + rem;

no = no / 10;
}

System.out.println(rev);

Output: 4737247

Step 2
j 1 2 3 4 5 6 7 i j
1       *       1 4
2     * * *     2 3, 4, 5
3   * * * * *   3 2,3, 4,5 ,6
1, 2, 3, 4, 5,
4 * * * * * * * 4 6, 7

Step3
j>=4 &&
1 j<=4
j>=3 &&
2 j<=5
j>=2 &&
3 j<=6
j>=1 &&
4 j<=7

j>=(5-i) && j<= (3+i)


OOPS concepts in Java:

Inheritance:
This represents a relationship through
which every property of parent class will
be by default available to the child.
This relationship can be establish by
using ‘extends’ keyword in which:
ClassA extends ClassB
Here A is extending ClassB that means
A will be having all properties available
to him from ClassB.
Example:
package oopsconcept;

public class Parent {

public void m1()


{
System.out.println("m1 of parent class");
}

public void m2()


{
System.out.println("m2 of parent class");
}

public static void m3()


{
System.out.println("static method of parent class");
}

public class Child extends Parent {

public static void m4() {


System.out.println("m4 method from child class");
}

public static void main(String[] args) {

Child c = new Child();


c.m1();
c.m2();
m3();
c.m3();
m4();

}
Output:
m1 of parent class
m2 of parent class
static method of parent class
static method of parent class
m4 method from child class
The main advantage of inheritance is
reusability that means we have to
define a code at a place which can be
use by multiple classes.
Parent can have multiple child classes
but converse is not possible.

A class can extend only one class at a


time that is multilevel inheritance is
possible but multiple inheritance is not
possible i.e to extend multiple class at a
time is not possible.
Cyclic inheritance is not possible.
Same class cannot inherit itself.
Example:
package oopsconcept;

public class SuperGrandParent {

public void sgm1()


{
System.out.println("Super grand parent's method is running");
}

}
package oopsconcept;

public class GrandParent extends SuperGrandParent {

public void gm1()


{
System.out.println("Grand parent method is running");
}
}
package oopsconcept;

public class Parent extends GrandParent {

public void m1()


{
System.out.println("m1 of parent class");
}

public void m2()


{
System.out.println("m2 of parent class");
}

public static void m3()


{
System.out.println("static method of parent class");
}

public static void main(String[] args) {


ElderChild c =new ElderChild();
c.m1();
c.m2();
c.m3();

Parent p = new Parent();


p.sgm1();

}
}
package oopsconcept;

public class ElderChild extends Parent {

public void m4() {


System.out.println("m4 method from child class");

public static void main(String[] args) {

ElderChild c = new ElderChild();


c.m1();
c.m2();
m3();
c.m3();
c.gm1();
c.sgm1();

Output:
m1 of parent class
m2 of parent class
static method of parent class
static method of parent class
Grand parent method is running
Super grand parent's method is running

Inheritance with respect to variable:

All global variable will be available to the child


class by default like methods.

If the same name of nonstatic variable is


available in parent class then in the non static
method we can access it through “super”
keyword. If we are accessing it through only
name then it points to the nearest non static
variable.

If the same name of static variable is available


into the parent and child class then we can
access the particular variable through class
name.variable name or if we are accessing it
through only name then it points to the nearest
static variable.

All global(class level) variables defined in the


subsequent parent classes can be accessible to
the child.

Example:
package oopsconcept;

public class Parent {

int i =10;
int j =60;

static int y = 20;

public void m1()


{
System.out.println("m1 of parent class");
}

public void m2()


{
System.out.println("m2 of parent class");
}

public static void m3()


{
System.out.println("static method of parent class");
}

public static void main(String[] args) {


ElderChild c =new ElderChild();
c.m1();
c.m2();
c.m3();

}
}
package oopsconcept;

public class ElderChild extends Parent {


int i = 50;

public void m4() {


int i = 20;
System.out.println("m4 method from child class");
System.out.println("The local variable i value is :" + i);// this is to
access local variable
System.out.println("The nonstatic variable i from parent class
value is :" + super.i);// this is to access

//
parent's class non

//
static variable
System.out.println("The nonstatic variable i from the same
class value is :" + this.i);// this is to access same

//
class non static
System.out.println(j);

// variable

public static void main(String[] args) {

ElderChild c = new ElderChild();

c.m4();

System.out.println("***********************************************");
System.out.println(c.i);// Accessing non static variable i from
the same class because same class and
// parent class has i variable.

System.out.println(y);// accessing static variable which is in


Parent class.
Parent p = new Parent();
System.out.println(p.i);// Accessing the parent's class non
static variable by parent object.
System.out.println(c.j);
}

Output:
m4 method from child class
The local variable i value is :20
The nonstatic variable i from parent class value is :10
The nonstatic variable i from the same class value is :50
60
***********************************************
50
20
10
60

Inheritance with respect to constructor:


 Child class Constructor will call automatically parent class
constructor in all cases(Whether constructor is present parent class
or not , if not present it will call default constructor of parent class.)

Example:

public class ParentConstructorClass2 {

public ParentConstructorClass2() {
System.out.println(" zero arg Constructor of parent class");

public class ChildConstructorClass extends ParentConstructorClass2 {

public ChildConstructorClass()

System.out.println("Zero arg of child class constructor");


}

public static void main(String[] args) {


ChildConstructorClass c = new ChildConstructorClass();

}
}
Output:

zero arg Constructor of parent class


Zero arg of child class constructor

 If Child class constructor type doesn’t matches with the parent then
specifically we have to call parent class constructor in the first line of
child by using super().

Example:

public class ParentConstructorClass2 {

public ParentConstructorClass2(int a)
{
System.out.println("PArent one argument constructor");
}

}
package oopsconcept;

public class ChildConstructorClass extends ParentConstructorClass2 {

public ChildConstructorClass()

{
super(20);
System.out.println("Zero arg of child class constructor");
}

public static void main(String[] args) {


ChildConstructorClass c = new ChildConstructorClass();

}
}

Output:
PArent one argument constructor
Zero arg of child class constructor

 Constructor doesn’t follow inheritance principle as all the


constructors available in parent class are not by default
available to child.
Example:
public class ParentConstructorClass2 {

public ParentConstructorClass2()
{
System.out.println("PArent's zero argument constructor");
}

public class ChildConstructorClass extends ParentConstructorClass2 {

public ChildConstructorClass(int i)
{

public static void main(String[] args) {


ChildConstructorClass c = new ChildConstructorClass();//
Compile time error because all constructors in parent class are not by
default available to child, hence constructor doesn’t follow inheritance
principle.

}
}
Polymorphism

Definition: Method having different forms with the same name is


called polymorphism.

Type of Polymorphism:

a. Overloading: A method can be called as Overloaded if and


only if the method name is same but the argument is different i.e
atleast order of the argument passes or data type of the
arguments.

b. Overloading is also known as Compile time polymorphism and


Early binding.

Reason: At the time of compilation of program for over loaded


method we get to know which method will get execute.

c. In Overloading method resolution is based on reference


variable.

Note: Overloading is applicable for inheritance as well.


Example:
package polymorphism;

public class Test {

public void m1(int i, int j)


{
System.out.println("m1 2 arguments method");
}

// method signature: name of method and its parameter

public void m1()


{
System.out.println("m1 of one argument");
}

public void m1(char c)


{
System.out.println("m1 of char argument is running");
}

public int m1(char i, int j) {

return 0;

public static void main(String[] args) {

Test t = new Test();


t.m1();
t.m1('a');

}
}

b. Overriding: A method can be called as Overridden method if the


name and signature in the child and Parent class is same.
Note: Method resolution is completely based on object.

b. Overriding is also known as run time polymorphism and Late


binding.

Reason: At run time of program for over ridden method we get to


know which method will get execute.

c. In Overriding method resolution is based on run time object.

If we declare method as final then we cannot override that


method

Example:
package polymorphism;

public class Test {

public void m1(int i, int j)


{
System.out.println("m1 2 arguments method");
}

// method signature: name of method and its parameter

public void m1()


{
System.out.println("m1 of zero argument from Test class");
}

public void m1(char c)


{
System.out.println("m1 of char argument is running");
}

public int m1(char i, int j) {

return 0;

package polymorphism;

public class Test2 extends Test {

String name = "hsdfhsdalkfhsadfhsajdfhsadjfhsdhfsdjkfhsjkdfhsdk";

public void m1(boolean b)

{
System.out.println("m1 of Test 2 with no argument");

public void m1() {


System.out.println("m1 of zero argument from Test2 class");
}
public static void main(String[] args) {
Test2 t = new Test2();
t.m1();

Test t1 = new Test();


t1.m1();

Output:
m1 of zero argument from Test2 class
m1 of zero argument from Test class

Example for Overloading and Overriding:


package polymorphism;

public class Parent {

public void m1()


{
System.out.println("m1 method of parent with 0 argument");
}

public void m1(int i)


{
System.out.println("m1 method of parent with 1 argument");
}
public void m2()
{
System.out.println("m2 method of parent with 0 argument");
}

}
package polymorphism;

public class Child extends Parent {

public void m1(int i, int j)


{
System.out.println("m1 method of child with 2 argument");
}

public void m2()


{
System.out.println("m2 method of child with 0 argument");
}

public static void main(String[] args) {

// 1 st object

Parent p = new Parent();


p.m1(10);// Parent's class method
p.m2();// Parent's class method

// 2nd Object

Child c = new Child();


c.m1(10, 20);//Child's class method
c.m1();// Parent class's method
c.m2();// Child's class method
//3 rd object

Parent pp = new Child();

pp.m1(10);//Parent's class method


pp.m2();// Child class method

}
}

Output:
m1 method of parent with 1 argument
m2 method of parent with 0 argument
m1 method of child with 2 argument
m1 method of parent with 0 argument
m2 method of child with 0 argument
m1 method of parent with 1 argument
m2 method of child with 0 argument

Note: Parent reference can be used to hold child object but converse is
not possible i.e child reference variable cannot be used to hold parent
Object.

Parent pp = new Child();--------- Valid


Child cc =new Parent(); // not valid in java

Overriding with respect to Static methods:


We cant override a static method as non static or either way after
doing the same we will get compile time error.

Reason: To access static we don’t need an object and for


nonstatic we always need to have an object.

Method hiding: If two static methods tries to get override then it


is not overriding but it is method hiding. That means method
resolution is based on reference type but not run time object.

Example:
package polymorphism;

public class Parent {

public static void marry()


{
System.out.println("marry method of parent with 0 argument");
}

package polymorphism;

public class Child extends Parent {

public static void marry()


{

System.out.println("Child's marry method");

}
public static void main(String[] args) {
Parent p = new Child();
p.marry();// Parent's static method will get execute

Child c = new Child();


c.marry();// Child static method will get execute

Parent pp = new Parent();


pp.marry();// Parent Static method will get execute

marry();// Child static method will get execute

}
Output:
marry method of parent with 0 argument
Child's marry method
marry method of parent with 0 argument
Child's marry method

Polymorphism with respect to variable:


Variable resolution always take care by compiler based reference type
whether the type of variable is static or non static. In short overriding
concept is not applicable to variables but only for methods
Example:
package polymorphism;

public class Parent {

int i = 20;
public static void marry()
{
System.out.println("marry method of parent with 0 argument");
}

}
package polymorphism;

public class Child extends Parent {

static int i = 10;

public static void marry()


{

System.out.println("Child's marry method");

public static void main(String[] args) {


Parent p = new Child();
p.marry();// Parent's static method will get execute
System.out.println(p.i);// Parent variable

Child c = new Child();


c.marry();// Child static method will get execute
System.out.println(c.i); //child variable

Parent pp = new Parent();


pp.marry();// Parent Static method will get execute

System.out.println(pp.i);// Parent variable


marry();// Child static method will get execute

System.out.println(i);// Child variable


}

}
Output:
marry method of parent with 0 argument
20
Child's marry method
10
marry method of parent with 0 argument
20
Child's marry method
10

Difference between overloading and Overriding:


Sr. no Characterstics Overloading Overriding
1 name must be same. must be same.
must be different
(atleast order of
2 Argument argument) must be same.
method
3 signature must be different must be same.
4 Return type no restrictions must be same.
If the scope of that modifier
gets increase then that method
5 Modifier no restrictions will get override
Method resolution
based on Reference
variable, that is it Method resolution based on run
method always takes care by time object that is it takes care by
6 resolutions Compiler jvm
Compile time
polymorphism, early
binding, Static Runtime polymorphism, Late
7 Also known as polymorphism binding, Dynamic polymorphism

Note : Main method can be overload but cannot Override.


public static void main(int [] args) {

Access Modifiers
Defination: The keyword which tells the accessibility of a particular method,
variable or class.

1. Access Modifier applicable to class:

i. public : - It can be accessible throughout the project.

ii. final : - Whichever class declared as final it cannot follow inheritance i.e
the class which has declared as final cannot be extended by another class.

Example 1: (final with public)

public final class ParentConstructorClass2 {

public ParentConstructorClass2()
{
System.out.println("PArent's zero argument constructor");
}

public class ChildConstructorClass extends ParentConstructorClass2


{//Compile time error saying to extend parentclass remove final modifier

public ChildConstructorClass()
{

public static void main(String[] args) {


ChildConstructorClass c = new ChildConstructorClass();

}
}

iii. <default>: The class which declares as <default> can be accessible


with in the package. We cannot access it outside of the package.

class ChildConstructorClass {

public ChildConstructorClass()
{

public static void main(String[] args) {


ChildConstructorClass c = new ChildConstructorClass();

}
}

Note: Here ChildConstructorClass is a default so it can be accessible within


the package where it has defined but not outside of the package.

Abstract

iv. abstract: A modifier which applicable to class and methods. If we don’t


have an idea of complete functionality i.e we know about the major part but
we are not sure about the implementation then we should declare or use
abstract modifier.

If we declare a class as abstract then it is not necessary to declare an


abstract method but if a class contains abstract method then we have to
declare that class as abstract.

Every child class of abstract class has to implement all the abstract
methods other wise we have to declare that class as abstract and have to
provide the implementation in subsequent child classes.
Example:

package abstractdiscussion;

public abstract class Test {

public void m1()


{
System.out.println("m1 method from Test");
}

public abstract void m2();

public abstract void m3();

public abstract void m4();

public abstract void m5();

package abstractdiscussion;

public class Test2 extends Test {

public void m2() {


System.out.println("m2 method implementation from test 2 class");

public void m3() {

System.out.println("m3 method implementation from test 2


class");
}
public void m4() {
System.out.println("m3 method implementation from test 2 class");

public void m5() {


System.out.println("m3 method implementation from test 2 class");

Example2:

package abstractdiscussion;

public abstract class Test {

public void m1()


{
System.out.println("m1 method from Test");
}

public abstract void m2();

public abstract void m3();

public abstract void m4();

public abstract void m5();

}
package abstractdiscussion;

public abstract class Test2 extends Test {


public void m2() {
System.out.println("m2 method implementation from test 2 class");

public void m3() {

System.out.println("m3 method implementation from test 2


class");
}

}
package abstractdiscussion;

public class Test3 extends Test2 {

public void m4() {


// TODO Auto-generated method stub

@Override
public void m5() {
// TODO Auto-generated method stub

We cannot create an object of abstract class but we can access the


complete methods from abstract class through child object.

Example:

package abstractdiscussion;
public abstract class Test {

public void m1()


{
System.out.println("m1 method from Test");
}

public abstract void m2();

public abstract void m3();

public abstract void m4();

public abstract void m5();

}
public abstract class Test2 extends Test {

public void m2() {


System.out.println("m2 method implementation from test 2 class");

public void m3() {

System.out.println("m3 method implementation from test 2


class");
}
public class Test3 extends Test2 {

public void m4() {

public void m5() {


}

public static void main(String[] args) {


Test3 t = new Test3();
t.m2();
t.m1();
}

Note: final cannot be used together with abstract.

Example for management of objects by using Abstract


class:
package abstractdiscussion;

public abstract class Test {

Test5 t5;
Test4 t4;

public Test()
{
t5 = new Test5();
t4 = new Test4();

}
}

package abstractdiscussion;

public class Test4 {

public void m2() {


System.out.println("m2 method of Test4");
}

public void m3() {


System.out.println("m3 method of Test4");
}
}
package abstractdiscussion;

public class Test5 {

public void m5() {


System.out.println("m5 method of Test5");
}
public void m6() {
System.out.println("m6 method of Test5");
}

package abstractdiscussion;

public class Test2 extends Test {

public void login()


{
t4.m2();
t5.m5();
}

public static void main(String[] args) {


Test2 t2 = new Test2();

t2.login();

}
Output:
m2 method of Test4
m5 method of Test5

Member level modifier:


1. public :- If we declare a method or a variable as public then the
visibility of that element is throughout the project.

public final class ParentConstructorClass2 {

public int i =10;

public void m2()


{
Test t = new Test();

Note: here this method visible to every class provided the class in which it
got defined is public.

2. <default>: If a particular method or variable declares as <default>


then it would be accessible throughout the package only.

public final class ParentConstructorClass2 {

int i =10;

void m2()
{
Test t = new Test();

3. private: If a particular method or variable is declared as private then


we can access method only in the class where it was defined.

public final class ParentConstructorClass2 {

private int i =10;


private void m2()
{
System.out.println("Private method ");

public static void main(String[] args) {


ParentConstructorClass2 p = new ParentConstructorClass2();
p.m2();
}

4. protected = <default>+ child classes


We can access the protected members with in the package as we are
doing in <default> but when we wants to access them outside the package
then we should use child reference only.

Example: From D class if we wants to access we should use D reference


only.

Example:

package oopsconcept;

public class A {

protected int i= 10;

protected void m1()


{
System.out.println("A class protected method");
}

}
package methodsdiscussion;

import oopsconcept.A;

public class B extends A {

public static void main(String[] args) {

A a = new A();

B b = new B();
b.m1();

}
package oopsconcept;

public class C {

public static void main(String[] args) {


A a = new A();
a.m1();
}

}
package methodsdiscussion;

public class D extends B {

public static void main(String[] args) {


D d = new D();
d.m1();

}
}

5. final: If we declare a variable as final then we cannot perform


reassignment of that variable except the place where it got initialized.
public final class ParentConstructorClass2 {

final static int i = 60;

public static void main(String[] args) {

i=50;// CE: We cannot reassign the value to variable i as it is a


final variable.

Scenario private default protected public

Within the same class Y Y Y Y

From the child class of N Y Y Y


same package

From the non child class of N Y Y Y


same package
From the child class of N N Y(We should Y
outside the package use child
reference only)
From the non child class N N N Y
outside the package

private< default<protected <public


Interface:
 Interface contains 100% abstract methods if we try to
define a method with body then it will be an error. Whenever
we are not sure about the complete logic for any of the
functionality then we should declare the particular class as
Interface.

 To implement an interface we have to use implements


keyword.

 If any class doesn’t wants to implement all of the methods


then we should declare that class as abstract and provide
the implementation in the child classes.

 Example:

package interfaceDiscussion;

public interface Interface1 {

public void m1();


public void m2();

}
package interfaceDiscussion;

public class Test implements Interface1 {

public void m1() {

public void m2() {

Example 2:
package interfaceDiscussion;

public interface Interface1 {

public void m1();

public void m2();

}
package interfaceDiscussion;

public abstract class Test implements Interface1 {


public void m1() {

public void m2() {

}
package interfaceDiscussion;

public class Test2 extends Test {

public void m2() {

 All the methods present inside an interface are by default


public and abstract whether we are declaring or not.

Example: package interfaceDiscussion;

public interface Interface1 {

void m1();

void m2();

}
Note: here m1 and m2 method are by default public .
Multiple inheritance from interface
Example:
package interfaceDiscussion;

public interface Interface1 {

void m1();

void m2();

}
package interfaceDiscussion;

public interface Interface2 {

public void m3();

public void m4();

}
package interfaceDiscussion;

public class Test implements Interface1, Interface2 {

public void m1() {

public void m2() {


}

public void m3() {

public void m4() {

Note: Multiple inheritance is possible with the help of


interface.

Example for calling method from Parent reference and child object.

package interfaceDiscussion;

public class Test implements Interface1, Interface2 {

public void m1() {

public void m2() {

public void m3() {


}

public void m4() {

public static void main(String[] args) {


Test t = new Test();
t.m1(); all Test class method will get execute

Interface1 i1 = new Test();


i1.m1();// in this case only overriding method will get execute
from Interface1 class only and additional method present in child class is
not get executed .for that we require child refrence.

Static method with respect to interface


We can have static method inside an interface provided we have the body
of the method as well. Static method cannot define without body inside an
interface.

Example:
package interfaceDiscussion;

public interface Interface2 {

public static void m3()


{
System.out.println("Static method from interface");
}

public void m4();

public static void main(String[] args) {


Interface2.m3();
}

}
Output: Static method from interface

Variable resolution with respect to interface:


Variables inside an interface are by default public static and final whether
we are declaring or not.

Reason for public: To access them from anywhere.

Reason for static: User should be able to access it without object creation.

Reason for final: As static variable shares its memory with all objects so
implemented class is not allowed to change its value.

Example:

package interfaceDiscussion;

public interface Interface2 {

int i =20;
int l = 40;
int b= 40;

Note:
Public static int I = 20;
Public static final int I = 20;
Public int I =20
All three of them are same inside interface.
Method having same name in different
interfaces:
Example:
package interfaceDiscussion;

public interface Interface1 {


int i =30;

void m1();

void m2();

package interfaceDiscussion;

public interface Interface2 {

int i = 20;
public void m1();
public void m2();

}
package interfaceDiscussion;

public class Test implements Interface1, Interface2 {

public void m1() {

public void m2() {

Note: If both interfaces have same name of methods in it then


the class which is providing the implementation have to define
those methods only once.

If both the interfaces method having the same signature but


return types are different so the class which implements those
interface will not be able to implement that method.

Example:
package interfaceDiscussion;
public interface Interface1 {
int i =30;

public void m1();

public void m2();

}
package interfaceDiscussion;

public interface Interface2 {

int i = 20;

public int m1();

public void m2();

}
package interfaceDiscussion;

public class Test implements Interface1, Interface2 {

public void m1() { // Error due to ambiguity of method definition in


both the interfaces.

}
public void m2() {
}

//x extends y---> x and y class as well as interface


//x extends y implements z --> x and y are classes and z is
interface
Difference between interface and abstract
Sr. No Interface abstract
If we don’t anything regarding If we know something
the implementation of the aboout the implementation
1
methods then we should then we should go for
prefer interface. abstract.
Every method is 100% Every method need not to
2
abstract. be abstract.
Methods in interface are
Method can be of any type
3 always by default public and
there is no restriction.
abstrat.
Variable inside interface are
Every variable inside the
always by default public static
4 abstract class need not be
and final whether we are
public static and final.
declaring or not.
Only public modifier is There is no such
5 applicable for methods and restrictions for the access
variables. modifier.
6 It cannot have constructor It can have constructor.
Encapsulation:

Encapsulation is just to the data and make


it available through hiding the internal functionality to the end user.

Encapsulation == Data hiding + Abstraction


Encapsulation can be achieved by declaring a variable as private inside a
class which is used by a public method. Later that method will be called by
other classes.

So here declaring variable as private is data hiding and calling


the public method to the other classes which is showing only the
functionality but not the implementation is Abstraction.

Example:

package encapsulation;

public class Test {

private double cust1bal = 10.00;

public double getBalance() {

return cust1bal;
}

}
package encapsulation;

public class Test2 {

public static void main(String[] args) {


Test t = new Test();

System.out.println(t.getBalance());

}
}
Output: 10.0

// OOPS concept have 3 pillers --- Inheritance, Polymorphism and


Encapsulation
Inheritance provides reusability

Polymorphism provides flexibility

Encapsulation provides security

Exception handling:
Definition:- Exception handling is nothing but to handle
the abnormal termination of a program into normal
termination. And make the program to execute completely
even though there is an exception caused during the
execution.

Example:
public class Test {

public static void main(String[] args) {

int i = 10;
int j = 0;
int k = i / j;
System.out.println(k);

Output: Exception in thread "main" java.lang.ArithmeticException: / by zero


at exceptionhandling.Test.main(Test.java:9)

There are two ways to handle the exception :


1. try-catch-finally
2. throws keyword
1. try-catch-finally:

a. try-catch
Example:

public static void main(String[] args) {


System.out.println("Before arrival of exception");
int i = 10;
int j = 0;
try {
int k = i / j;
}

catch (ArithmeticException message)


{
System.out.println("Catch of Arithmatic exception is running "+
message.getMessage());

System.out.println("After handling of exception");

Output:
Before arrival of exception
Catch of Arithmatic exception is running / by zero
After handling of exception
Note:
If the type of exception which is inside the try block is
covered by catch block then the exception will get handle
and the program gets terminate in a normal way.

If the type of exception inside try block is not been


covered by any of the catch blocks then the program
would get terminate abnormally.

B. try-catch- finally

 Inside try block we generally writes the risky code


which can cause an exception
 In the catch block we writes the code which can tell
us to by pass the situation on which we got an
exception. Only that particular catch will get execute
which has written for that particular exception. For
example if in try block we gets Arithmatic exception
then there should be a catch block with Arithmatic
exception otherwise program will get terminate
abnormally.
Finally block executes every time whether we gets
an exception or not. It is basically to perform clean up
activities.
Example with finally:
package exceptionhandling;

public class Test {

public static void main(String[] args) {


System.out.println("Before arrival of exception");
int i = 10;
int j = 0;
try {
int k = i / j;
System.out.println("try second line");
System.out.println("try third line");

catch (ArithmeticException message)


{
System.out.println("Catch of Arithmatic exception is running "+
message.getMessage());

finally {

System.out.println("finally block is running");

System.out.println("After handling of exception");


}

}
Output:
Before arrival of exception
Catch of Arithmatic exception is running / by zero
finally block is running
After handling of exception

Interview question:
Difference between final –finally – finalize:
Finalize() is a method which generally called by garbage collector to cut
off the remaining connections of the unused object and destroy the same
for memory optimization.

c. try-finally
try with finally is also a valid combination here finally will
get execute after try block whether we get an exception or
not.
Example:
package exceptionhandling;

public class Test {

public static void main(String[] args) {


System.out.println("Before arrival of exception");
int i = 10;
int j = 0;
try {
int k = i / j;
System.out.println("try second line");
System.out.println("try third line");

}
finally {

System.out.println("finally block is running");

System.out.println("After handling of exception");

}
Output:
Before arrival of exception
finally block is running
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exceptionhandling.Test.main(Test.java:10)

Note: try-catch-finally or try-catch or try-finally must be the immediate


blocks after each other. There should not be any java statement between
them.

Example:

package exceptionhandling;

public class Test {

public static void main(String[] args) {


System.out.println("Before arrival of exception");
int i = 10;
int j = 0;
try {
int k = i / j;
System.out.println("try second line");
System.out.println("try third line");

catch(ArrayIndexOutOfBoundsException aa)
{

catch (NullPointerException e) {

}
catch(NumberFormatException ee)
{

}
catch (ArithmeticException message)
{
System.out.println("Catch of Arithmatic exception is running "+
message.getMessage());

}
catch(Exception e)
{
System.out.println("try second line");
}

finally {

System.out.println("finally block is running");

}
}

Unchecked Category:
Those exception which can cause at the runtime comes under unchecked
category. All the Runtime exception classes and Error are the part of
Unchecked exception.

Checked Category:
Those exception which has to be handle at the compile time only comes
under checked category. All the IO exception classes are the part of
checked exception.

Example:
public static void main(String[] args) {
System.out.println("Before arrival of exception");
int i = 10;
int j = 0;
try {
Thread.sleep(5000);

catch (InterruptedException e) {
System.out.println("Interrupted exception Catch block");
}

System.out.println("After completion of 5 sec");

Throws Keyword:
By using throws keyword we can handle the compile
time error for exception handling but if there is an
exception caused during runtime then it cannot
protect from Abnormal termination of program.
It is recommended to use throws keyword for
checked exception.

Using throws keyword


public static void main(String[] args) throws InterruptedException {
System.out.println("Before arrival of exception");
int i = 10;
int j = 0;
Thread.sleep(5000);

Throw Keyword:
By using throw keyword we can throw the exception
at a particular situation in the program.
It is generally used for throwing customize exception
(Exceptions which are defined by user).
Example :

int i = 10;
int j = 20;

if (i > 5) {
throw new ArithmeticException("Morning batch exception
handling testing");

}
if (j > 20) {

System.out.println("No exception caused during the program");

}
Output:
Exception in thread "main" java.lang.ArithmeticException: Morning batch
exception handling testing
at exceptionhandling.Test.main(Test.java:11)
Array
Collection of homogenous data type is called an array.
To define an array there are two ways:
int[] intarray = new int[5];
i 0 1 2 3 4
0 0 0 0 0

int [] a = {10, 20, 30};


10 20 30

package arraydiscussion;

public class ArrayTest {

public static void main(String[] args) {

int[] intarray = new int[5];// defination of array

// initialization of array

intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
intarray[3] = 40;
intarray[4] = 50;

System.out.println(intarray[4]);// to get a particular value


for (int i = 0; i < 5; i++)// using for loop to print all the values of
array
{
System.out.println(intarray[i]);
}

}
Output:
50
10
20
30
40
50

Length: length is a variable which provides the size


of array
For example:
intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
intarray[3] = 40;
intarray[4] = 50;
intarray[5] = 30;
intarray[6] = 40;
intarray[7] = 50;

int size = intarray.length;

System.out.println("the size of array is :"+size);

for(int i=0; i<size; i++)


{
System.out.println(intarray[i]);
}

Note: If user tries to put more than the length of array elements then we
get ArrayIndexOutOfBoundException.

For example:

package arraydiscussion;

public class ArrayTest {

public static void main(String[] args) {

int[] intarray = new int[5];// defination of array

int [] a = {10, 20, 30};

for(int i=0; i<3; i++)


{
System.out.println(a[i]);
}

// initialization of array

intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
intarray[3] = 40;
intarray[4] = 50;
intarray[5] = 30;
intarray[6] = 40;
intarray[7] = 50;

int size = intarray.length;

System.out.println("the size of array is :"+size);


for(int i=0; i<size; i++)
{
System.out.println(intarray[i]);
}

}
Output:
10
20
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at arraydiscussion.ArrayTest.main(ArrayTest.java:24)
30

To handle above exception:

package arraydiscussion;

public class ArrayTest {

public static void main(String[] args) {

int[] intarray = new int[5];// defination of array

int [] a = {10, 20, 30};

for(int i=0; i<3; i++)


{
System.out.println(a[i]);
}

// initialization of array
try {
intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
intarray[3] = 40;
intarray[4] = 50;
intarray[5] = 30;
intarray[6] = 40;
intarray[7] = 50;
}
catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array overflow");

int size = intarray.length;

System.out.println("the size of array is :"+size);

for(int i=0; i<size; i++)


{
System.out.println(intarray[i]);
}

}
OutPut:
10
20
30
Array overflow
the size of array is :5
10
20
30
40
50

For each loop:


for(int aa:intarray)
{
System.out.println(aa);
}

Example:
public static void main(String[] args) {

int[] intarray = new int[5];// defination of array

// initialization of array

intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
intarray[3] = 40;
intarray[4] = 50;

// for each loop

for (int aa : intarray) {


System.out.println(aa);
}

Output:

10
20
30
40
50

Array can be used as an argument to the


method:
Example:

int[] intarray = new int[5];// defination of array

// initialization of array

intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
intarray[3] = 40;
intarray[4] = 50;

public void m1(int[] a) {


a[0] = 50;

for (int b : a) {
System.out.println(b);
}

public static void main(String[] args) {

ArrayTest t = new ArrayTest();


t.m1(intarray);
}

Output:

50
20
30
40
50

Method with return type of Array:


public class ArrayTest {

public int[] m3()


{
int [] a = {1, 2, 3};
return a;
}

public static void main(String[] args) {

ArrayTest t = new ArrayTest();

for(int aaaa:t.m3())
{
System.out.println(aaaa);
}
}

Output :

1
2
To sort an array in ascending order:
We have a static method called sort() in Arrays class.

Example:

public static void main(String[] args) {

int[] intarray = new int[7];// defination of array

// initialization of array
intarray[0] = 80;
intarray[1] = 70;
intarray[2] = 10;
intarray[3] = 90;
intarray[4] = 100;
intarray[5] = 50;
intarray[6] = 26;
System.out.println("********************Before
sorting***********************");
for(int aa:intarray)
{
System.out.println(aa);
}

System.out.println("********************After
sorting************************");
Arrays.sort(intarray);
for(int aa:intarray)
{
System.out.println(aa);
}

Output:

********************Before sorting***********************
80
70
10
90
100
50
26
********************After sorting************************
10
26
50
70
80
90
100

Type casting:
To convert a type of entity to another type is called type casting.

There are 2 types of type casting:


1. Upcasting:
Where the type of variable is converted to higher order data type is called
upcasting. It is also called widening or broadening of variable. While
performing up casting there is no loss of information. For example: byet to
int conversion it is also known as generalization
public static void main(String[] args) {

byte b = 10;
int v = (int)b;// upcasting because here byte is getting convert
to higher order i.e integer

System.out.println(v);

Output:

10

2. Downcasting:
Where the type of variable is converted to lower order data type is called
downcasting. It is also called narrowing of variable While performing down
casting there can be loss of information. For example: int to byte
conversion it is also know as specialization

int i = 129;
byte c = (byte)i;

System.out.println(c);// downcasting because here integer is


getting convert to lower order i.e byte
Output:

-127

Rules applicable for different data types manipulation:

byte + byte = int


short + short = int
byte + short = int
int + int = int
int + long = long

long + double = double

Example with respect to methods in which type casting is used:

package typecasting;

public class Test {

String s = "jsdhfsjdhfshdfjskdfshkdjfhs";

public void m1(int i)


{
System.out.println(i);
}

public byte m2()


{
byte x = 10;
return x;
}

public static void main(String[] args) {

byte b = 10;
int v = (int) b;// upcasting because here byte is getting convert
to higher order i.e integer
System.out.println(v);

int i = 129;
byte c = (byte) i;

byte d = 1;

System.out.println(c);// downcasting because here integer is


getting convert to lower order i.e

System.out.println(c);

Test t = new Test();


int z = (int)t.m2();//here we are type casting the byte value to
the int so that we should be able to use it

t.m1(z);

}
Output:

10
-127
-127
10

If we wants to type cast classes then we must have relation between


those like parent and child.

Type casting w.r.t classes:

Implicit type casting:(lower to upper)


Whenever child class is type cast to parent then it is called implicit type
casting

Example:

A is parent class

B is Child class

// implicit type casting in which the lower class will type cast to the upper
// class(Parent class)

B b = new B();
b.m1();// m1 method of class B

A aa = (A) b;

aa.m1();// m1 method of class B

Explicit type casting:( upper to lower)


Whenever Parent class is type cast to Child then it is called Explicit type
casting.

A a = new A();
a.m1();// m1 method of class A

// Explicit casting in which parent class will get type cast to


the child class

B bb = (B) a;// here we are trying to hold parent object by child


reference hence this gives an exception called ClassCastException

bb.m1();// this will not execute


String Discussion:
String is class present in java.lang package.

String can be defined through two ways:

1. String s = new String(“def”);

If we create in this way then 2 objects will get created one in heap area
and another in SCP area(String constant pool area).

2. String ss = “abc”;

If we create in this way then only one object will get created in SCP area.

Note: for any same content new object will not get create in SCP it will
first check whether the object with the same content is available or not
Memory management of String class.

// (s1.equals )......equals method is used for content comparison


// == is used for reference comparison

if (ss==s)
{
System.out.println("same object");
}
else
System.out.println("different object");

Important methods in String class:


1. charAt(int index):

This is to get the value of character at a particular index.


Example:
String s = "abc";
char charatsecondindex = s.charAt(2);
System.out.println(charatsecondindex);// c

Note: If the opted char value is beyond the string range we would get
Exception

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:


String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at stringclassdiscussion.Test.main(Test.java:15)

2. concat(String s) :
This method is used to join two strings.
Example:

//concat
String joinedone = s.concat("xyz");or s.concat(ss)
System.out.println(joinedone);

Output: abcxyz
Note:String is immutable in nature as the value of the objct doesn’t gets
change with respect to any operation.

Example:

s.concat("xyz");

System.out.println(s);//abc

3. Equals(Object o):

This method is used to check the content whether it is exactly


matching with the referring one by considering letter case as
well.(i.e..case sensitive)
// equals

boolean ismatch = s.equals("abc");


System.out.println(ismatch);

Output: true

public static void main(String[] args) {


String s = "abc";
String ss = "Abc";
boolean isequal = s.equals(ss);
System.out.println(isequal);

Output: false

4. equalsIgnoreCase(String anotherstring):
This is to compare two strings whether they are equal or not in
terms of content by ignoring the case of letter.
Example:

public static void main(String[] args) {


String s = "abcDDDE";

String ss = "AbcdDDe";

boolean isequals = s.equalsIgnoreCase(ss);


System.out.println(isequals);

Output: true

5. substring(int beginindex):

This method is to create another string from the given string by


mentioning index number.
For Example:

String s = "abcDDDE";
String substr = s.substring(3);
System.out.println(substr);

Output:

DDDE

6. substring(int beginindex, int endindex):


This method is to create another string by considering begin
index value to the endindex value -1.
String s = "abcDDDE";

String substttr = s.substring(2, 5);


System.out.println(substttr);

Output: cDD

7. length():
This method returns the length of a particular string. Length is
actually maximum index +1.
For Example:

String str = "123456abcdef";

int leng = str.length();


System.out.println(leng);

Output: 12
8. replace(char old, char new):
This method is used to replace the character with another
character.
String sss = "ababa";

String replacedstring = sss.replace('a', 'b');


System.out.println(replacedstring);

Output: bbbbb

9. toLowerCase():
This method is used to convert the given string into lowercase.
For Example:

String cases = "AB1FDD";


String lcase = cases.toLowerCase();
System.out.println(lcase);

Output: ab1fdd

9. toUpperCase():
This method is used to convert the given string into uppercase.
For example:

String ucases= "shkjsdhA";


String changeduppercase = ucases.toUpperCase();
System.out.println(changeduppercase);

Output: SHKJSDHA
10. trim():
This method is used to clear the space which is associated with
it as prefix and suffix.
For example:

String withspaces = " Value ";

String general = "driven";

String withoutspaces = withspaces.trim();


System.out.println(withoutspaces+" "+general);

Output: Value driven

11. indexOf(char ch):


This method returns index value of particular character in a
string.
String ind = "abcdefa";

int index = ind.indexOf('f');


System.out.println("index value is :"+index);

Output: index value is :5

12. lastIndexOf(int ch):


This method is to return the last appear index value of a
character available in a string.
// lastIndexOf
String lind = "abadefa";

int indexvalue = lind.lastIndexOf('a');


System.out.println(indexvalue);

Output: 6

13. contains(String charsequence):


This method is used to match the particular sequence into a
string and returns true if it got matches and false if it doesn’t.
//contains(String charactersequence)

String d = "abcdefghidef";

boolean ispresent = d.contains("def");


System.out.println(ispresent);

Output: true

14. toCharArray():

This method is used to convert the string into character


array.
Example:

//toCharArray();

String str1 = "abcdefghi";

char[] stringarray = str1.toCharArray();


for(int i =0; i<stringarray.length; i++)
{
System.out.println(stringarray[i]);
}

for(char ch :stringarray)
{
System.out.println(ch);
}
Output:

a
b
c
d
e
f
g
h
i
a
b
c
d
e
f
g
h
i

15. isDigit(Char ch):


This method is to check whether the given character is digit or
not.
Example:

//isDigit()

char cc = '1';
boolean isdigitavailable = Character.isDigit(cc);
System.out.println(isdigitavailable);
Output: true

To convert primitive to String :


//to convert primitive data to string

int z = 123;

String convertedint = String.valueOf(z);


System.out.println(convertedint+3);
Output: 1233

To convert String to Primitive :

// to convert String to primitive

String bln = "true";

boolean convertedboolean = Boolean.parseBoolean(bln);


if(convertedboolean)
{
System.out.println("Boolean value has been converted");

}
Output:
Boolean value has been converted
16. split(String regex):
This method is used to split the string.
Note : to split the string by the help of space the we have to pass \\s in
the ().

// split

String tobesplit = "Abcxy cdwer";

String[] splittedstring = tobesplit.split("\\s");


for(String sp:splittedstring)
{
System.out.println(sp);
}

Output:

Abcxy
cdwer

String tobesplit = "Abcxycdwer";

String[] splittedstring = tobesplit.split("c");


for(String sp:splittedstring)
{
System.out.println(sp);
}

Output:

Ab
Xy
dwer
Collection:
1. It is a framework which comprises of numerous
interfaces.
2. Definition: Collection is a group of individual objects
which re represented by a single entity.
3.

ArrayList©:
1. In arraylist duplicates are allowed.
2. All types of datatype are applicable but in order to use
ArrayList class we should prefer generics. i.e <generics>.

Collection examples:
Arraylist:
Example:
package collectiondiscussion;

import java.util.ArrayList;

public class CollectionPractice {


public static void main(String[] args) {

// Default size = 10
// if 11th element comes then the new size would be =
oldsize * (3/2)+1= 16
ArrayList<Integer> al = new ArrayList<Integer>();

al.add(10);// add a value inside the ArrayList


// al.add("String");
// al.add(false);
// al.add("String");
// al.add(false);

al.add(20);
al.add(30);// this method will add the value to the
collection
al.remove(0);// it will remove the value from the
arraylist

al.set(1, 50);// this will replace the value

// al.clear();// this will clear the complete arraylist


//
// boolean isclear = al.isEmpty();// checks the arraylist is
empty or not
//
// System.out.println(isclear);// true

System.out.println(al);

}
}
Output:
[20, 50]
Some more methods available in the classes of collection:
al2.removeAll(al);// this method will remove al collection from al2
collection
boolean iscollection = al2.containsAll(al);// this method
checks whether al2 contains all the elements of al
System.out.println("al2 contains all the elements of al is
:"+iscollection);

ArrayList<Integer> al3 = new ArrayList<Integer>();

al3.add(100);
al3.add(500);
al3.addAll(al2);
al3.addAll(al);// this method is to add all the elements from
al to al3.

al3.retainAll(al);// this method will retain al collection and


remove the others.

System.out.println(al3);

Conversion from Array to collection and vice versa


package collectiondiscussion;

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayToCollection {

public static void main(String[] args) {

String[] s = new String[3];

s[0]= "abc";
s[1]= "def";
s[2]= "ghi";

ArrayList<String> al = new
ArrayList<String>(Arrays.asList(s));

System.out.println(al);
// to convert collection to array

ArrayList<String> al2 = new ArrayList<String>();


al2.add("123");
al2.add("456");
al2.add("789");

String [] str = new String[al2.size()];

al2.toArray(str);

for(String ss:str)
{
System.out.println(ss);
}

}
}

Cursor:
It is an element which is always pointing before the
first element of any collection. It is basically used to
iterate collection values one by one.
There are three types of cursor:
1. Enumertion--- which is only applicable to legacy
classes. It can perform only read operation.
Legacy class: The class which got introduced in 1.0
version of java.
For example: Vector is a legacy class.
2. Iterator: It is applicable to all collection framework.
Iterator is also known as universal cursor. Remove
operation can be done.
3. List Iterator: It is applicable to only list classes.
List iterator is used to perform add, remove and
replace operation.
package collectiondiscussion;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;

public class CursorsInCollection {

public static void main(String[] args) {

// Vector<String> v= new Vector<String>();


//
// v.add("abc");
// v.add("def");
//
// // only read operation is applicable to enumeration
// Enumeration<String> e = v.elements();
//
//
// while(e.hasMoreElements())
// {
// String ss = e.nextElement();
// System.out.println(ss);
// }

// ArrayList<String> al = new ArrayList<String>();


//
//
// al.add("abc");
// al.add("def");
// al.add("ghi");
//
// Iterator<String> itr = al.iterator();
//
// while(itr.hasNext())
// {
// String ss = itr.next();
// if(ss.equals("abc"))
// {
// itr.remove();
// }
//
// System.out.println(ss);
//
// }
// System.out.println(al);

// list iterator

ArrayList<String> al = new ArrayList<String>();


//
//
al.add("abc");
al.add("def");
al.add("ghi");

ListIterator<String> lstr1 = al.listIterator();

while(lstr1.hasNext())
{
String ss = lstr1.next();
lstr1.add("jkl");
if(ss.equals("abc"))
{
lstr1.remove();
}
if(ss.equals("def"))
{
lstr1.set("mno");
}

System.out.println(ss);
}

while(lstr1.hasPrevious())
{
String sss = lstr1.previous();

System.out.println(sss);

Hash Set: In this the functionality would be same but we don’t


allow duplicates inside it.
Insertion order is also not preserved.
package collectiondiscussion;

import java.util.ArrayList;
import java.util.HashSet;

import org.apache.poi.hpsf.Array;

public class SetDiscussion {


public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();

al.add("Ram");
al.add("Shyam");
al.add("Sita");
al.add("geeta");
al.add("Ravi");
al.add("Monty");

System.out.println(al);

HashSet<String> hs = new HashSet<String>(al);

System.out.println(hs);

}
Output:
[Ram, Shyam, Sita, geeta, Ravi, Monty]
[Monty, Shyam, Sita, Ravi, geeta, Ram]// hashset data here
insertion order is not preserved.

LinkedHashSet: A class in which duplicates are not allowed


but insertion order is also preserved.
Selenium

Selenium Basics
To download selenium go to:

https://www.selenium.dev/downloads/

To download ChromeDriver go to :

https://chromedriver.chromium.org/downloads

To configure selenium
Click on Add external jar
For more details:

https://github.com/SeleniumHQ/selenium/blob/e6f1131dae8fd9
7a27bd7d9a2efc618821c76bd8/java/client/src/org/openqa/sele
nium/SearchContext.java#L22
Selenium:
An open source tool which provides the functionality of
automating the webbase/mobile application by using different
programming language. The version 3.14 is the latest stable
version of selenium.

Advantages of Selenium Disadvantages of Selenium

1) Selenium is an Open Source Selenium does not automate


Software captcha and barcode,image and
video and audio.

2) Selenium supports various Selenium only works on the web


programming languages to write based applications.
programs (Test scripts)

3) Selenium supports various Difficult to use, takes more time to


operating systems (MS Windows, create Test cases.
Linux, Macintosh etc…)

4) Selenium supports various Selenium depends on third party


Browsers (Mozilla Firefox, Google frameworks like TestNG, Cucumber
Chrome, IE, Opera, Safari etc…) for the reporting

) Selenium supports Parallel Test New features may not work


Execution properly

Selenium uses less Hardware No Built-in Reporting facility


resources
What is searchContext?
SearchContext is an Interface which provides two
important methods.
SearchContext is the super interface of the
Webdriver,which is extended by another interface
called WebDriver. All the abstract methods of
SearchContext and WebDriver interfaces are
implemented in RemoteWebDriver class.
findElement
findElements

What is Selenium WebDriver Interface?


Selenium WebDriver is an interface that defines a set of methods.

The WebDriver main functionality is to control the browser. It even helps


us to select the HTML page elements and perform operations on them
such as click, filling a form fields etc

The object of the webdriver is a browser.

However, implementation is provided by the browser specific classes.


Some of the implementation classes are AndroidDriver, ChromeDriver,
FirefoxDriver, InternetExplorerDriver, IPhoneDriver, SafariDriver etc.
What is selenium remote webdriver?
Selenium remotewebdriver implements the webdriver interface to execute
test cases on remote server.

Thebr
owserdr
ivercl
asses
l
ike,
Fir
efoxDr
iver
,Chr
omeDr
iver
,I
nter
net
Expl
orer
Dri
ver
,et
c.ext
endt
he
Remot
eWebDr
ivercl
ass

What is Selenium Grid?


Selenium Grid is a part of the Selenium Suite that specializes in running
multiple tests across different browsers, operating systems, and
machines in parallel.

A user needs to configure the remote server in order to execute the tests.

Selenium Grid uses a hub-node concept where you only run the test on a
single machine called a hub, but the execution will be done by different
machines called nodes.

Example: To launch the browser:


get(String url):- This method is used to redirect to the url which
has been entered by the user.

Example:
To execute the test on different browser on a particular condition:
Note: Always we have to create the reference variable of
WebDriver because for any particular condition if the browser
gets change then we don’t have to create a new object. With the
same reference variable we can do so.

Some basic commands:


Locators in Selenium:

Locators: It is the address of a particular webelement


through which we can perform the operations on it.
Types of locator:

1. id
2. classname
3. name
4. xpath
5. text()
6. link text
7. partial link text.

To locate a particular webelement we have to rightclick if it is a


button or click over it and right click if it is a text field
1 id
To locate an element by use of id we have to follow the following
steps:

1. Right click on the element which we wants to locate.

2. Select the inspect option from the rightclick menu

3. find out the id from the highlighted html line.

Note: If we are not able to locate a particular element then we will


get an exception and that is NoSuchElementException from
selenium.
2. by name:
To find an element by using name in the html code.

3. xpath:
In order to use xpath we have to write the expression in a
particular syntax:

//<tagname>[@attribute_name= ‘attribute_value’]
Shortcut key to run webelement on inspect is
(ctrl+F)
Note: Whenever we have multiples nodes matching and we don’t have any
other options for the other attributes then we should follow:

(//input[@type='text'])[2]
2. If we donot mention the tage name inside the xpath then also by using *
in the place of tagname we can execute it as previously. For example

//*[@id='txtUsername']

X path with contains: If there are some characters


of attribute which gets change dynamically (with
respect to time) then it is prefer to use contains in
the xpath which provides the flexibility to create the
xpath by using some of the characters.
Example:
//*[contains(@id, 'txtUser')]

Xpath with logical parameters


Example:
//*[@id='txtUsername' and @name = 'txtUsername']
This will match only when there are both of the
xpath are correct.
By using or
//*[@id='txtUsername' or @name = 'txtUsername']
This will match when either of the path is match.

4.getText(): This method is used to return the text


of the webelement.
For example:

Xpath using text():


Syntax:
//<tagname>[text()= ‘text value’]
Example:
<div id="logInPanelHeading">Velocity</div>
//div[text()=’Velocity’]
By using contains:
//*[contains(text(),'Velo')]

6. By linkText():
This is to locate a webelement by using the actual
link text for a webelement.
For example:
<a href="/index.php/auth/logout">Logout</a>
Here logout is a linktext and it can be calclulated
through link text.
Example:
driver.findElement(By.linkText("Logout")).click();

Code to login and logout from Orange


HRM:
public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan 21\\Downloaded\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://opensource-
demo.orangehrmlive.com/index.php/auth/login");

driver.manage().window().maximize();

driver.findElement(By.xpath("//*[@id='txtUsername']")).sendKeys("Admin");

driver.findElement(By.xpath("//*[@id='txtPassword']")).sendKeys("admin12
3");

driver.findElement(By.xpath("//*[@id='btnLogin']")).click();

Thread.sleep(2000);

driver.findElement(By.xpath("//*[@id='welcome']")).click();

Thread.sleep(2000);

driver.findElement(By.linkText("Logout")).click();

7. partialLinkText():
This is to locate an element over a webpage by entering
the link partially.
For example:
public static void main(String[] args) {
driver.findElement(By.xpath("//*[@id='txtUsername']")).sendKeys("Admin");

driver.findElement(By.xpath("//*[@id='txtPassword']")).sendKeys("admin12
3");

driver.findElement(By.partialLinkText("Forgot your
p")).click()
}

Absolute and Relative xpath:

Absolute xpath: xpath which gets frame by using only single forward
slash ‘/’ is called absolute x path.
It contains the complete path from the Root Element to the desire element.

but the disadvantage of the absolute XPath is that if there are any changes
made in the path of the element then that XPath gets failed.
Absolute xpath are generally not preferable to use as they gets
change dynamically.
copy as full xpath is known as absolute xpath.

Relative xpath: The xpath which gets frame by using double forward
slash “//” is called relative xpath.
It can search elements anywhere on the webpage, means no need to write
a long xpath and you can start from the middle of HTML DOM structure.
Advantage of relative is that we can traverse from parent to child
by skipping the intermediate rows.
This is highly preferable over the other kind of xpaths.
Copy as xpath is known as relative xpath.
Handling of drop down by using selenium:
findElements():
This method is to find the multiple
webelements over the webpage.
For example:

To select the value from the drop down using find elements:
Handling of drop-down by using select class:

Checkboxes handling
Code to check the checkboxes alternatively
Dynamic X path: The x path which get forms on the fly i.e at the
time of execution of script we append a value which get combines to form
a xpath is called dynamic x path for example in the above code the value of
i has been taken as the variable which gets vary dynamically.

isSelected(): This method returns true when the particular


check boxes or radio button is selected or not.

isEnabled(): This method returns true when the particular


check boxes or radio button is in clickable state.

isDisplayed():This method returns true when the particular


check boxes or radio button is displaying over the webpage or not.
getAttribute(String str): This method is used
to get the attribute value of a particular attribute.
For example:
<a href="/index.php/admin/viewAdminModule"
id="menu_admin_viewAdminModule"
class="firstLevelMenu"><b>Admin</b></a>

WebElement admin =
driver.findElement(By.xpath("//*[@id='menu_admin_viewAdminModule']"));

String attrivalue = admin.getAttribute("id");

System.out.println(attrivalue);

Output:

menu_admin_viewAdminModule

Xpath for calendar handling:

//tbody//tr//td//a[text()='12']
Scrolling commands in selenium
To scroll into selenium we have to do
following steps:
1. type case the webdriver reference
variable.
2. call execute script method.
3. enter the command in the form of string.
For example to scroll in the particular
direction:
Example 2:
To scroll to a particular element over a
webpage:

Alternate to click method in selenium by


using javascript executor:
WebElement checkbox =
driver.findElement(By.xpath("//*[@id='ohrm
List_chkSelectRecord_25']"));
JavascriptExecutor js =
(JavascriptExecutor)driver;
js.executeScript("arguments[0].click();",
checkbox);// alternate to click method in
selenium
Handling of multiple windows in Selenium

To handle the multiple window we have to use


getWindowHandle() and getWindowHandles().
getWindowHandle(): This method provides the
parent id of the particular browser. This method
returns the string as an output.
getWindowHandles(): This method provides
the set<String> which contains all the active
windows id in it.This method returns the set of
Strings.
For example:
To switch to the particular window and
perform the operation:
To store the window ids to the array:

Output:
Parent id is :CDwindow-269838D97216808A0185C3300ABBB2ED
CDwindow-269838D97216808A0185C3300ABBB2ED
CDwindow-A5506B23B39636E912C58CA1737A6206
CDwindow-D38FFDE37C5A80D5FD10C67EE2ADBCE3

http://demo.automationtesting.in/Datep
icker.html
Date handling.

DatePicker handling
ACTIONS KEYWORD

Actions class is an ability provided by Selenium for handling keyboard and


mouse events. In Selenium WebDriver, handling these events includes
operations such as drag and drop, clicking on multiple elements with the
control key, among others.

Autosuggestion:

act.sendKeys(textfield,Keys.ARROW_DOWN).sendKeys(Keys.AR
ROW_DOWN).sendKeys(Keys.ENTER).build().perform();
Keyup and keydown:
Keyup and keydown is basically are the methods which
are used to copy and paste the content into a particular
field by the use of Actions class
Hover effect :
Hover effect can be done with the help of Action class. To
hover on a particular element we have to use
moveToElement(WebElement).
// hover effect on a particular element

Actions act = new Actions(driver);


act.moveToElement(Admin).perform();

Right click on an element using Action class:


To right click on an element we have to use
contextClick(WebElement) method.
For example:Actions act = new Actions(driver);
// act.contextClick(maintenance).perform();

To double click on the element:


For double click on the element we have to use
doubleClick(WebElement) method

// to double click on element

WebElement doubleclick =
driver.findElement(By.xpath("//*[@id='double-click']"));

act.doubleClick(doubleclick).perform();
Click and hold using action class:

WebElement letterA =
driver.findElement(By.xpath("//*[@id='sortable']//li[text()='A']"));
//
// WebElement letterC =
driver.findElement(By.xpath("//*[@id='sortable']//li[text()='C']"));
Actions act = new Actions(driver);

act.clickAndHold(letterA).moveToElement(letterC).click().
build().perform();

To practice slider functionality :


https://jqueryui.com/slider/

Iframe:
This is a special frame which has a special kind of
functionality which is embedded over the webpage. To
perform the operation to that frame we first have to
switch to the frame and then perform the operation.
Alert Handling:
The pop up are those which cannot be inspected
means their x path or locator cannot be calculated.

There are basically 3 types of alert popup:


1. Alert with ok button.
2. Alert with ok and close button.
3. Child browser pop-up(Inspectable)

1. Alert with ok button

System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://chercher.tech/practice/practice-pop-
ups-selenium-webdriver");

driver.manage().window().maximize();
WebElement doubleclick =
driver.findElement(By.xpath("//*[@id='double-click']"));

act.doubleClick(doubleclick).perform();

//Pop ups:
//1 Alert popup-
//2. Alert popup with accept and dismiss button
//3. Child browser popup

Thread.sleep(1000);

String textonalert = driver.switchTo().alert().getText();


System.out.println(textonalert);

driver.switchTo().alert().accept();

driver.switchTo().alert().dismiss();

Child browser popup handling:


The pop up which can be inspectable over the browser are called
as child browser popup.
To handle these we have to take the locator and perform the
actions.

ScreenShot in Selenium for failed cases


Waits in selenium or Synchronization in
selenium:
Waits are nothing but the dynamic
component which waits for a particular
event and once it founds it move forwards
irrespective of the time remaining hence
they are called as dynamic waits.

There are 3 types of dynamic waits:


1. implicit wait.:- This is also known as
global wait because once it applies at a
point it will be applicable to all the web
elements available below it. On the
completion of configured time it throws the
NoSuchElement exception.

For example:
driver.get("https://groww.in/");
driver.manage().window().maximize();

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

WebElement title = driver.findElement(


By.xpath("//*[@class='btn51Btn
btn51RipplePrimary
btn51Primary']//span[text()='Login/Register']"));

title.click();

driver.findElement(By.xpath("//*[@id='login_email1']")).sendKeys("
velocity.ctc@gmail.com");

driver.findElement(
By.xpath("(//*[@class='absolute-center
btn51ParentDimension']//*[@class='absolute-center'])[2]"))
.click();

// Actions act = new Actions(driver);

WebElement pwd =
driver.findElement(By.xpath("//*[@id='login_password1']"));

// act.sendKeys(pwd, "gou781990").build().perform();

pwd.sendKeys("gou781990");
driver.findElement(By.xpath("//*[@class='absolute-
center btn51ParentDimension']//span[text()='Submit']"))
.click();

ii.Timeout with waits: This is to verify the actual the page is


taking time before it gets load completely over the screen. If it
doesn’t load within the specified time then it throws
TimeOutException.

It can be configurable i.e we can use different time units.

2. Explicit wait:The Explicit Wait in Selenium is used to tell


the Web Driver to wait for certain conditions (Expected Conditions)
or maximum time exceeded before throwing
"ElementNotVisibleException"
This only verifies whether that element is available or not but for
the particular conditions we won’t be able to use it. For that
purpose we have to use explicit wait.

Complete handling of explicit with condition:


public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://chercher.tech/practice/explicit-wait-sample-selenium-
webdriver");

driver.manage().window().maximize();

WebDriverWait wait = new WebDriverWait(driver, 60);//Explicit wait

driver.findElement(By.xpath("//*[@id='enable-button']")).click();

wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='disable']")));

driver.findElement(By.xpath("//*[@id='enable-button']")).click();

Example to handle alert dynamically:


//wait till the alert gets open
driver.findElement(By.xpath("//*[@id='alert']")).click();

wait.until(ExpectedConditions.alertIsPresent());

Thread.sleep(1000);

driver.switchTo().alert().accept();

Example to handle text dynamically


//wait till the text to be present

driver.findElement(By.xpath("//*[@id='populate-text']")).click();

wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//*[@id='h2']"),
"Selenium Wedfsdfbdriver"));

driver.findElement(By.xpath("//*[@id='populate-text']")).click();

// wait till the checkbox gets check


driver.findElement(By.xpath("//*[@id='checkbox']")).click();

wait.until(ExpectedConditions.elementSelectionStateToBe(By.xpa
th("//*[@type='checkbox']"), true));

driver.findElement(By.xpath("//*[@id='checkbox']")).click();

Note: Thread.sleep is a static wait which


will wait for a specified time irrespective of
condition whether the element is available
or not but all the other waits like implicit,
explicit and fluent wait are the dynamic one
that means if any thing gets found it will not
wait for the configured time and move
forward to the next step.

3 Fluent wait:
Fluent wait have the ability to poll, timeout
and exception which can be configured
according to the requirement.
Syntax:
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(50, TimeUnit.SECONDS)
.pollingEvery(9, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

wait.until(ExpectedConditions.elementSele
ctionStateToBe(By.xpath("//*[@type='check
box']"), true));
Read and write in
excel sheet
Step 1
Download the third party tool that is apache
poi from:
http://poi.apache.org/download.html
Step 2: Extract the downloaded zip.
Step 3: move all the jars from the different
folders to one location.
Step 4: Right click to the project and say
build path ---- Configure build path ---- add
external jars.

Example to read the data:


package utility;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReader {

public static void main(String[] args) throws IOException {

//to get the path of the variable and let the java know
about it
File src = new
File("C:\\Users\\A\\Desktop\\SampleTestData.xlsx");

// to load the file


FileInputStream fis = new FileInputStream(src);

// load the workbook or excel file


XSSFWorkbook wb = new XSSFWorkbook(fis);

// to get the sheet from the workbook


XSSFSheet sh1 = wb.getSheetAt(0);

String value = sh1.getRow(1).getCell(1).getStringCellValue();

System.out.println(value);
}

Read the data and use it in the test script:

Write the data into excel sheet


public static void writeData() throws IOException {

// to get the path of the variable and let the java know about it

// File src = new


File("C:\\Users\\A\\Desktop\\SampleTestData.xlsx");

File src = new File(System.getProperty("user.dir") +


"//TestData//SampleTestData.xlsx");

// to load the file

FileInputStream fis = new FileInputStream(src);

// load the workbook or excel file

XSSFWorkbook wb = new XSSFWorkbook(fis);

// to get the sheet from the workbook

XSSFSheet sh1 = wb.getSheetAt(0);

File fout = new File(System.getProperty("user.dir") +


"//TestData//SampleTestData.xlsx");

FileOutputStream fo = new FileOutputStream(fout);

// for existing row and column

// sh1.getRow(5).getCell(0).setCellValue("TestData");
//

// sh1.getRow(6).getCell(0).setCellValue("TestData1");

// For row is not existing

sh1.createRow(5).createCell(2).setCellValue("Fiftyth row");

wb.write(fo);

}
Readdat
afr
om pr
oper
ti
esf
il
e
Usageofpr
oper
ti
esf
il
e:
1.Whenev
erwef
eel
thedat
ais
f
requent
lyget
ti
ngchanget
henwe
shoul
dusepr
oper
ti
esf
il
e.
2.Whenev
erwewant
stoconf
igur
eout
t
estscr
iptt
oapar
ti
cul
arf
lowt
henal
so
weuset
his.

Ex
ampl
e:

publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
t
hrowsI
OEx
cept
ion{
Sy
stem.
set
Proper
ty(
"webdr
iver
.chr
ome.
dr
iver
","
E:\
\Deskt
op\
\Vi
manNagar
\\Jan
21\
\Downl
oaded\
\chr
omedr
iver
.ex
e")
;
Pr
oper
ti
espr
op=newPr
oper
ti
es(
);
WebDr
iverdr
iver=newChr
omeDr
iver
();

Fi
leI
nput
Str
eam f
is=new
Fi
leI
nput
Str
eam(
Syst
em.
get
Proper
ty(
"u
ser
.di
r"
)+"
\\Conf
ig.
proper
ti
es"
);

pr
op.
load(
fi
s);

/
/tor
eadt
hedat
afr
om
conf
ig.
proper
ti
esf
il
e
St
ri
ngur
l=
pr
op.
get
Proper
ty(
"test
sit
eur
l"
);

Sy
stem.
out
.pr
int
ln(
url
);
dr
iver
.get
(pr
op.
get
Proper
ty(
"test
sit
eur
l"
)
)
;
dr
iver
.manage(
).
window(
).
max
imi
ze(
);

dr
iver
.f
indEl
ement
(By
.xpat
h("
//*
[@i
d='
tx
t
User
name'
]
"))
.sendKey
s(pr
op.
get
Proper
t
y("
user
name"
));

dr
iver
.f
indEl
ement
(By
.xpat
h("
//*
[@i
d='
tx
t
Passwor
d']
")
).
sendKey
s(pr
op.
get
Proper
t
y("
passwor
d")
);
dr
iver
.f
indEl
ement
(By
.xpat
h("
//*
[@i
d='
bt
nLogi
n'
]"
)).
cli
ck(
);

Read and Write code for excel in a


customized manner:
package utility;

public class ExcelReader {

public static String readData(int row, int column, String filename) throws
IOException {

// to get the path of the variable and let the java know about it

// File src = new File("C:\\Users\\A\\Desktop\\SampleTestData.xlsx");

File src = new File(System.getProperty("user.dir") +


"//TestData//"+filename+".xlsx");
// to load the file

FileInputStream fis = new FileInputStream(src);

// load the workbook or excel file

XSSFWorkbook wb = new XSSFWorkbook(fis);

// to get the sheet from the workbook

XSSFSheet sh1 = wb.getSheetAt(0);

// if we wants to get the numeric value

CellType type = sh1.getRow(row).getCell(column).getCellType();

String value = "";

if(type==CellType.NUMERIC)
{

double number =
sh1.getRow(row).getCell(column).getNumericCellValue();

int intnumber = (int)number;

value = String.valueOf(intnumber);

else
{

value =
sh1.getRow(row).getCell(column).getStringCellValue();

System.out.println(value);

return value;

TestNG- Framework
TestNG stands for testing new generation, it is
a framework which allow the user to decide the
conditions and configuration for a specific or
multiple test cases and generate a report after
the completion of execution.
Critical features of testNG:
1. We can decide whether testcase is passed or
fail or skipped on a particular.
2. After the execution emailable report is
available.
3. Description can be added for a test case.
4. We can group the testcase according to the
requirement.
5. We can decide the priority i.e which testcase
will execute first and which one at last.
6. We can create multiple test cases by using
multiple data.
7. We can execute the testcases in parallel.
Installation part:
First way:
Go to help --- Eclipse market place--- Type
testng and click on go
Click on install button and it will get download
and install automatically.
Second way:
Go to help ---- install new software---- paste this
url-https://dl.bintray.com/testng-team/testng-eclipse-release/ in work with field.

Sequence of test case execution


Without any keyword: We have not use any
keyword which decides the execution order, in
this case the execution will depends on
dictionary order of the test case name.
With keyword i.e priority: If we set the priority
to the test case then the execution will happen
according to it.

Default value of priority would be 0.


Priority of the test case can be :
a. –ve value
b. +ve value
c. 0 value
d. duplicate

Priority cannot be:


a. decimal value
b. variable
Reporter class in testng
Reporter class is a class in testng which
has a log method that gives functionality
to user for mentioning the messages
inside the html report as well as in the
console(Standard input output media) .
Example:
@Test
public void testCase2() {
Reporter.log("TC2", false);
}

enabled keyword
If we wants to ignore a particular test case from
an execution process then we can write enabled
=false
For example:
@Test(enabled= false)
public void testCase5() {
Reporter.log("TC3", true);
}

Invocation keyword
We can execute a particular test method
multiple times (say 5 times) with the help of the
invocationCount helper attribute.

@Test(invocationCount=5)
public void testCase5() {
Reporter.log("TC3", true);
}

Annotations in TestNG:
1. @Beforemethod: This annotation containing
method will get execute when we wants some
precondition to execute before @Test.
1. @Aftermethod: This annotation containing
method will get execute when we wants some
Postcondition to execute after @Test.

Example:
package testngdiscussion;

import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class AnnotationsInTestNG {

@BeforeMethod
public void beforeMethod()
{
Reporter.log("before method", true);
}

@Test
public void case1()
{
Reporter.log("test case 1", true);
}

@Test
public void case2()
{
Reporter.log("test case 2", true);
}
@AfterMethod
public void afterMethod()
{
Reporter.log("After method", true);
}

}
Output:
before method
test case 1
After method
before method
test case 2
After method
Note :Before method will get execute before @Test and
Aftermethod will get execute after the completion of @Test.

3. @BeforeClass: This annotation’s method will execute


before the start of any thing from that class.

4. @AfterClass: This annotation’s method will execute after


the completion of the methods of that class.

Example:
package testngdiscussion;

import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class AnnotationsInTestNG {

@BeforeClass
public void beforeClassMethod()
{
System.out.println("Before class is executing");
}

@BeforeMethod
public void beforeMethod()
{
Reporter.log("before method", true);
}

@Test
public void case1()
{
Reporter.log("test case 1", true);
}

@Test
public void case2()
{
Reporter.log("test case 2", true);
}

@AfterMethod
public void afterMethod()
{
Reporter.log("After method", true);
}
@AfterClass
public void afterClassMethod()
{
System.out.println("After class is executing");
}

}
Output:
Before class is executing
before method
test case 1
After method
before method
test case 2
After method
After class is executing

Note : In order to control the execution of


multiple test classes or if we wants to impose
any condition on the class then we should
create xml file so that we can control it.
To create xml we have to right click on any of
the class which we wants to control and go to
TestNG and select convert to TestNG.
@Before Test: This execute before the
execution of test tag.

@AfterTest: This annotation gets execute


after the completion of test tag
Note: here test tag refers to the xml file.

@BeforeSuite: This annotation execute


before the start of suite of a particular xml file.

@AfterSuite: This annotation execute after


the completion of suite of a particular xml
file.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Vimannagar">
<test name="Jan Batch morning">
<classes>
<class name="testngdiscussion.AnnotationsInTestNG"/>
<class name="testngdiscussion.AnnotationsInTestNG2"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Example with xml and class:


package testngdiscussion;

import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class AnnotationsInTestNG {

@BeforeSuite

public void beforeSuite()


{
Reporter.log("Before suite", true);
}
@BeforeTest
public void beforeTest()
{
System.out.println("Before test annotation from testng
class");
}

@AfterTest
public void afterTest()
{
System.out.println("after test annotation from testng
class");
}
@AfterSuite

public void afterSuite()


{
Reporter.log("after suite", true);
}

@BeforeMethod
public void beforeMethod()
{
Reporter.log("before method", true);
}

@Test
public void case1()
{
Reporter.log("test case 1", true);
}

@Test
public void case2()
{
Reporter.log("test case 2", true);
}

@AfterMethod
public void afterMethod()
{
Reporter.log("After method", true);
}

@AfterClass
public void afterClassMethod()
{
System.out.println("After class is executing");
}

@BeforeClass
public void beforeClassMethod()
{
System.out.println("Before class is executing");
}

}
package testngdiscussion;

import org.testng.Reporter;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class AnnotationsInTestNG2 {


@Test
public void testCase3()
{
Reporter.log("Test case 3 from TestNG2 class", true);

}
@AfterTest
public void afterTest()
{
System.out.println("After test annotation");
}
@BeforeTest
public void beforeTest()
{
System.out.println("Before test annotation from testng2
class");
}

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Vimannagar">
<test name="Jan Batch morning">
<classes>
<class name="testngdiscussion.AnnotationsInTestNG"/>

</classes>
</test> <!-- Test -->
<test name="Jan Batch evening">
<classes>

<class name="testngdiscussion.AnnotationsInTestNG2"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Output:
Before suite
Before test annotation from testng class
Before class is executing
before method
test case 1
After method
before method
test case 2
After method
After class is executing
after test annotation from testng class
Before test annotation from testng2 class
Test case 3 from TestNG2 class
After test annotation
after suite
Assertions in TestNG:
Assertion in testng helps to evaluate the actual
status of the test case whether it got pass or
fail based on the particular condition.

There are 2 types of asserts:


a. Hard assert
b. Soft assert
a. Hard Assert: In this assert if the test got
failed at any of the line then further it wont
execute that particular test case, directly it will
mark it as failed and move on to the next test
case.
For example:
Assert.fail();
Assert.assetEquals(actual, Expected, message);
Example from the script:
package testngdiscussion;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class AssertionExamples {

@Test
public void login() throws IOException
{
System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");
Properties prop = new Properties();

WebDriver driver = new ChromeDriver();

FileInputStream fis = new


FileInputStream(System.getProperty("user.dir") +
"\\Config.properties");

prop.load(fis);

// to read the data from config.properties file

String url = prop.getProperty("testsiteurl");


System.out.println(url);

driver.get(prop.getProperty("testsiteurl"));

driver.manage().window().maximize();

driver.findElement(By.xpath("//*[@id='txtUsername']")).sendKeys(
prop.getProperty("username"));

driver.findElement(By.xpath("//*[@id='txtPassword']")).sendKeys(
prop.getProperty("password"));

driver.findElement(By.xpath("//*[@id='btnLogin']")).click();

String loginerrormessage =
driver.findElement(By.xpath("//*[@id='spanMessage']")).getText();

//applying the check point interms of assertion

Assert.assertEquals(loginerrormessage,
"Invalid credentialss", "Text not got matched
hence failing");

System.out.println("Assertion got executed");

driver.navigate().refresh();
driver.get("https://meet.google.com/gvv-hnwq-vdx");

}
@Test
public void testCase2()
{

System.out.println("this test case 2");

}
}

b. Soft assert: This assert will complete all


the test steps inside the @Test method but at
the last it will mark that particular test case as
pass or fail.
To evaluate we have to call assetAll() on that
basis the result get evaluated.
To use soft assert first we have to create an
object of SoftAssert Class.
For example:
@Test
public void loginWithSoftAssert() throws IOException
{
System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");
Properties prop = new Properties();
WebDriver driver = new ChromeDriver();

FileInputStream fis = new


FileInputStream(System.getProperty("user.dir") +
"\\Config.properties");

prop.load(fis);

// to read the data from config.properties file

String url = prop.getProperty("testsiteurl");

System.out.println(url);

driver.get(prop.getProperty("testsiteurl"));

driver.manage().window().maximize();

driver.findElement(By.xpath("//*[@id='txtUsername']")).sendKeys(
prop.getProperty("username"));

driver.findElement(By.xpath("//*[@id='txtPassword']")).sendKeys(
prop.getProperty("password"));

driver.findElement(By.xpath("//*[@id='btnLogin']")).click();

String loginerrormessage =
driver.findElement(By.xpath("//*[@id='spanMessage']")).getText();

//applying the check point as Soft assert interms of


assertion
SoftAssert sa = new SoftAssert();
sa.assertEquals(loginerrormessage, "Invalid
credentialss", "Text not got matched hence failing");

System.out.println("Assertion got executed");

driver.navigate().refresh();
driver.get("https://meet.google.com/gvv-hnwq-vdx");

// to decide the final status of the test case


sa.assertAll();
}

Depends on Method
This keyword allow the user to make a
dependency over a method and execute the
dependent method only if the method on which
it get depends get execute.
If the method got failed then the dependent
method will get skip.
For Example: (With in the same class)
@Test(priority = 1)
public void testCase()
{

Reporter.log("Login failed");

@Test(priority = 2, dependsOnMethods= "testCase")


public void testCase1()
{

Reporter.log("Login failed");
// Assert.assertEquals("Login", "Dashboard");

@Test(dependsOnMethods = {"testCase1"} , priority =3 )


public void testCase2()
{

System.out.println("Dashboard");
Assert.assertEquals(true, false);

Example (If method is in different classes)


package testngdiscussion;

import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;

public class DependsOnMethod {


@Test(priority = 1)
public void testCase()
{

Reporter.log("Login failed");

@Test(priority = 2, dependsOnMethods= "testCase")


public void testCase1()
{

Reporter.log("Login failed");
// Assert.assertEquals("Login", "Dashboard");

@Test(dependsOnMethods = {"testCase1"} , priority =3 )


public void testCase2()
{

System.out.println("Dashboard");
Assert.assertEquals(true, false);

}
package testngdiscussion;

import org.testng.Reporter;
import org.testng.annotations.Test;

public class DependsOnMethods2 {


@Test(priority = 4, dependsOnMethods=
"testngdiscussion.DependsOnMethod.testCase2")
public void testCase4()
{

Reporter.log("Test case 4 has executed", true);

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="testngdiscussion.DependsOnMethod"/>
<class name="testngdiscussion.DependsOnMethods2"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Output:
Include & exclude a specific method :
If we want to include only a particular method
from a class then we should include keyword in
testng.xml file.
For example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class
name="testngdiscussion.InclusionAndExclusionOfMethods">
<methods>

<include name="testCase2"></include>
<include
name="extraMethod"></include>
</methods>
</class>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

To exclude a method from a class then :


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class
name="testngdiscussion.InclusionAndExclusionOfMethods">
<methods>

<exclude name="testCase5"></exclude>

</methods>
</class>

</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Approach in TestNG to execute only the


test case which got failed in the previous
execution:
We have to first refresh the folder test-output folder
in which we have a xml by testng-failed.xml file. If
we execute that file then all the test case which got
failed will get execute.

To execute a particular group in the test


class:
We can execute a particular group or we can
exclude a particular group of test cases by
using grouping of test cases.
While grouping the execution of only testcases
can be done we cannot execute any other
annotation.

For Example:
To exclude a group from the execution:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<groups>
<run>

<exclude name="Regression"></exclude>
</run>

</groups>

<classes>
<class name="testngdiscussion.GroupingOfTestCases"/>
<class name="testngdiscussion.GroupingOfTestCases2"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
package testngdiscussion;

import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;

public class GroupingOfTestCases {

@Test(groups = "Regression")
public void testCase1() {
Reporter.log("TC1 from test2", true);

System.out.println("TC1");
}

@Test(groups = "Sanity")
public void testCase2() {
Reporter.log("TC2 from test2", false);
}

@Test(groups = "Regression")
public void extraMethod() {
Reporter.log("Extra method from test2",
true);
Assert.fail("Assertion failed
deliberately");

@Test(groups = {"Sanity", "Regression"})


public void testCase3() {
Reporter.log("TC3 from test2", true);

}
@Test
public void testCase5() {
Reporter.log("TC3 from test2", true);
}

@Test
public void testCase6() {
Reporter.log("This is testcase 6 which
executes multiple times from test2", true);

Parallel execution in TestNG:


We can execute the test cases in parallel
according to the <test>,Classes and
methods.
Note:
1. For methods executing in parallel these will
get execute parallel according to the class
execution order. i.e for any class all the
methods will get execute in parallel manner but
class execution sequence remains the same.
2. For classes execution in parallel all the
classes mentioned in the <test> will execute in
parallel but every class method inside a
particular class will follow the sequence.
3. For <test> execution in parallel where all the
<test> will get execute in parallel manner.
For example: Classses execution in parallel
manner:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test" thread-count="8" parallel="classes">
<classes>
<class
name="testngdiscussion.ParallelExecutionOfClasses"/>
<class
name="testngdiscussion.ParallelExecutionOfClasses2"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
package testngdiscussion;

import java.util.Properties;

import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;

public class ParallelExecutionOfClasses {

@Test
public void testCase1() {
Reporter.log("TC1 ", true);

System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");

WebDriver driver = new ChromeDriver();


driver.get("https://www.google.com/");
System.out.println("TC1");
}
}
package testngdiscussion;

import java.util.Properties;

import org.openqa.selenium.WebDriver;
import
org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;

public class ParallelExecutionOfClasses2 {

@Test
public void extraMethod() {

System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");

WebDriver driver = new ChromeDriver();


driver.get("https://www.google.com/");
Reporter.log("Extra method ", true);
}
}

Example for executing the <test> in parallel:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests">
<test name="Test1" thread-count="8" parallel="classes">
<classes>
<class
name="testngdiscussion.ParallelExecutionOfClasses"/>
<class
name="testngdiscussion.ParallelExecutionOfClasses2"/>
</classes>
</test> <!-- Test -->

<test name="Test2" thread-count="8" >


<classes>
<class
name="testngdiscussion.ParallelExecutionOfClasses3"/>
<class
name="testngdiscussion.ParallelExecutionOfClasses4"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Note: In the above xml <test> Test1 has parallel class as well
which will get execute in parallel manner.

Parameterization in TestNG:
In this we can obtain the value from xml file and
use the same to the Test case according to our
requirement.

For example:
package testngdiscussion;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParameterInTestNG {


@Test(enabled =false)
@Parameters ("browser")
public void testCase1(String name)
{
System.out.println(name);

if(name.equalsIgnoreCase("Chrome"))
{
System.out.println("Chrome browser
specific test case");
}
else if
(name.equalsIgnoreCase("Firefox"))
{
System.out.println("FireFox browser
specific test case");
}
}

@Test
@Parameters ({"browser", "buildver"})
public void testCase2(String name, String
build)
{
System.out.println(name);
System.out.println(build);

}<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests">
<test name="Test" >
<parameter name="browser" value="Firefox"></parameter>
<parameter name="buildver" value="0.0.121"></parameter>
<classes>
<class name="testngdiscussion.ParameterInTestNG"></class>

</classes>
</test> <!-- Test -->

<test name="Test2">
<parameter name="browser" value="Chrome"></parameter>
<parameter name="buildver" value="0.0.122"></parameter>
<classes>
<class name="testngdiscussion.ParameterInTestNG"></class>

</classes>
</test>
</suite> <!-- Suite -->

Example 2: @parameter with one data:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" >

<test name="Test" >


<parameter name="browser" value="Firefox"></parameter>

<classes>
<class name="testngdiscussion.ParameterInTestNG"></class>
</classes>
</test> <!-- Test -->

</suite> <!-- Suite -->

TestNG Listeners
TestNG Listeners are the one which always
listen the activity i.e if a test case gets pass
then perform an activity task is carried out by
listeners.
It can be done by implementing iTestListener
interface.
For example applying listener to the single
class:
package testngdiscussion;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestNGListeners implements ITestListener{

@Override
public void onTestStart(ITestResult result) {

System.out.println("Starting of Test case


:"+result.getName());

@Override
public void onTestSuccess(ITestResult result) {
System.out.println("Test case
Passed:"+result.getName());

@Override
public void onTestFailure(ITestResult result) {
System.out.println("Test case
Failed:"+result.getName());

@Override
public void onTestSkipped(ITestResult result) {
System.out.println("Test case
Skipped:"+result.getName());

@Override
public void
onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
}

@Override
public void onStart(ITestContext context) {

System.out.println("Starting the
process:"+context.getName());

@Override
public void onFinish(ITestContext context) {
System.out.println("Finishing the
process:"+context.getName());

}
package testngdiscussion;

import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners (TestNGListeners.class)
public class TestClassForLiteners {

@Test(priority = 1)
public void testCase1()
{
Reporter.log("testcase 1 ", true);
}

@Test(priority = 2)
public void testCase2()
{
Reporter.log("testcase 2 ", true);
}

@Test(priority = 3)
public void testCase3()
{
Reporter.log("testcase 3 ", true);

Assert.fail();
}

@Test(priority = 4, dependsOnMethods ="testCase3" )


public void testCase4()
{
Reporter.log("testcase 4 ", true);
}

What is Page Object Model?


Page Object Model (POM) is a design pattern, popularly used in test
automation that creates Object Repository for web UI elements. The
advantage of the model is that it reduces code duplication and improves test
maintenance.

Under this model, for each web page in the application, there should be a
corresponding Page Class. This Page class will identify the WebElements of
that web page and also contains Page methods which perform operations on
those WebElements.

The Page Object Design Pattern provides the following advantages:


There is a clean separation between test code and page specific code such as locators (or
their use if you’re using a UI Map) and layout.

There is a single repository for the services or operations offered by the page rather than
having these services scattered throughout the tests.

In both cases this allows any modifications required due to UI changes to all be made in
one place. Useful information on this technique can be found on numerous blogs as this
‘test design pattern’ is becoming widely used. We encourage the reader who wishes to
know more to search the internet for blogs on this subject. Many have written on this
design pattern and can provide useful tips beyond the scope of this user guide.

Uses of Page Object Model (POM):


This Design Pattern is used in Selenium where web pages are represented by a
corresponding class and web elements are represented by the variables of the
class and all interactions are possible through the methods or say functions of
the class.
Advantages of POM model:
Reusability: We can reuse the page class if required in different test cases
which means we don’t need to write code for identifying the web elements
and methods to interact with them for every test case.
Maintainability: As we can see from the above picture test case and page
class are different from each other which means we can easily update the
code if any new web element is added or existing one updated.
Readability: As we can see in the above picture page code is separated form
test code which helps to improve code readability.

Page Object Design Pattern says operations and flows in the UI should be
separated from verification. This concept makes our code cleaner and easy to
understand.

The Second benefit is the object repository is independent of test cases, so


we can use the same object repository for a different purpose with different
tools. For example, we can integrate Page Object Model in Selenium with
TestNG/JUnit for functional Testing and at the same time with
JBehave/Cucumber for acceptance testing.

Code becomes less and optimized because of the reusable page methods in
the POM classes.

Methods get more realistic names which can be easily mapped with the
operation happening in UI. i.e. if after clicking on the button we land on the
home page, the method name will be like 'gotoHomePage()'.
Maven build Life cycle:

Build Lifecycle Basics


Maven is based around the central concept of a build lifecycle. What this means is that the process
for building and distributing a particular artifact (project) is clearly defined.
For the person building a project, this means that it is only necessary to learn a small set of
commands to build any Maven project, and the POM will ensure they get the results they desired.
There are three built-in build lifecycles: default, clean and site. The default lifecycle handles your
project deployment, the clean lifecycle handles project cleaning, while the site lifecycle handles the
creation of your project's site documentation.

A Build Lifecycle is Made Up of Phases


Each of these build lifecycles is defined by a different list of build phases, wherein a build phase
represents a stage in the lifecycle.
For example, the default lifecycle comprises of the following phases (for a complete list of the
lifecycle phases, refer to the Lifecycle Reference):

validate - validate the project is correct and all necessary information is available

compile - compile the source code of the project

test - test the compiled source code using a suitable unit testing framework. These tests should
not require the code be packaged or deployed

package - take the compiled code and package it in its distributable format, such as a JAR.
verify - run any checks on results of integration tests to ensure quality criteria are met

install - install the package into the local repository, for use as a dependency in other projects
locally

deploy - done in the build environment, copies the final package to the remote repository for
sharing with other developers and projects.

These lifecycle phases (plus the other lifecycle phases not shown here) are executed sequentially to
complete the default lifecycle. Given the lifecycle phases above, this means that when the default
lifecycle is used, Maven will first validate the project, then will try to compile the sources, run those
against the tests, package the binaries (e.g. jar), run integration tests against that package, verify the
integration tests, install the verified package to the local repository, then deploy the installed
package to a remote repository.

A Build Phase is Made Up of Plugin Goals


However, even though a build phase is responsible for a specific step in the build lifecycle, the
manner in which it carries out those responsibilities may vary. And this is done by declaring the
plugin goals bound to those build phases.
A plugin goal represents a specific task (finer than a build phase) which contributes to the building
and managing of a project. It may be bound to zero or more build phases. A goal not bound to any
build phase could be executed outside of the build lifecycle by direct invocation. The order of
execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example,
consider the command below. The clean and package arguments are build phases, while the
dependency:copy-dependencies is a goal (of a plugin).

Maven life cycle


Selenium framework is a code structure for
making code maintenance simpler, and code
readability better. A framework involves breaking the
entire code into smaller pieces of code, which test a
particular functionality
Types of Framework:
Data driven: If there is lot of test data available to drive the test case then it is called data
driven framework.
Example: Data from excel sheet will cause change of flow.

Keyword driven: If a particular word is used to detect a particular flow is called key word driven.

Hybrid Framework: If a framework is the combination of multiple types of framework is


called hybrid framework.
Requirements of Framework for testing:
1. We don’t have to manage the jars inside the project this part
should be managed by the framework itself.

2. Once we shared it the team it will directly be executable.

3. Detailed analysis tool should be available after the execution.

4. Can be executed through different ways.

Maven Project

Maven is a build automation tool which compile and build the


project according to the jars version available in the pom.xml file
and execute the complete project.
Creation of Maven Project:

Step 1:

Select the project.

Step 2: Click on Maven and select Maven Project followed by click


on the next button.
Click on Next and then again click on Next.

Step 3: Select the encircled type and click on the next button

Step 4: Provide Artifact ID and groupId then click on Finish button.


Step 5: Add all the dependencies followed by create packages
inside src/main/java by the name of pages and create package
testcases inside src/test/java.

Step 6: Write the code into them.

Step 7: To compile the code on java 8 we require maven compiler


plugin and to configure our test execution we have to provide
testng.xml file inside the pom.xml configuration by adding maven
surefire plugin.

To use maven compiler pluggin copy the xml code from:

https://maven.apache.org/plugins/maven-compiler-
plugin/usage.html

To use maven surefire plugin:

https://maven.apache.org/surefire/maven-surefire-
plugin/usage.html

To copy the extent report selenium jar:

https://mvnrepository.com/artifact/com.aventstack/extentrepor
ts

Modules present:
Total modules: 15 to 20

Pom class in each module: 20-30

Total pom classes: 400 to 600

Test cases in each module: 70-100

Test cases in each Test class: 5 to 10 (7 avg)

Test classes in each module: 10-20

src/main/java- All pom classes

src/test/java- All test classes

src/main/java or src/main/java - library files/config files

Scenarios for Investment Banking:

Investment Banking(Kite Zeroda) Project Scenarios

1. Quantity field should by default 1

2. when we click on stock it should show buy ,sell,view chart and


other details

26. wishlist--add/remove

3. while selecting order if we select CNC (cash and carry ) order


,we can hold the stock for long term --manual

4. While Selecting order,if we select MIS(margine intraday sqare)


it should automatically exit at 3-20 pm

5. if you try to place order ,but you don't have fund in your
account then it should display insufficient fund msg

6. if you forget to logout account,at end of every day it should


automatically logged out --manual

7. when we placed the order by selecting market price ,price field


should be disabled

8. when we placed limit order price field should be editable

9. when we placed bracket order(BO) then stoploss, target,


trailing Stop loss should enable

10. when we placed cover order (co) only Stop loss field enabled

11. price field should accept value in multiple of 0.05 (eg


55.05,55,56.15 etc accepted) (55.06,55.07 not accepted)

12. after placing order ,in orders tab it will show Executed or
pending orders

13. in portfolio tab , should show holdings and position of stock.

14. after clicking on user id tab it should show customer details

15. in options quantity field should accept in Lott eg ( 25 for


banknifty,75 for nifty, depends on stock)

16. while adding fund in your demat account ,after clicking on


add fund button , different payment options should enabled

17. when we click on withdraw button , withdrawal amount field


and proceed button should enabled.
18. when we click on recent withdrawal option,it should show
our withdrawal activities

19. when we click on AMO (after market order) option, we should


able to placed order after market timing--manual

20. at time of order placing, BSE Or NSE only one should enabled

21. when we click on chart it should show different formats of


chart (eg 1d,5d,1M etc ) d- day,M- month

22. application should show same price of stock as per NSE or


bse ,if we open an application in different platforms or machines,
mobile etc

24. if we placed withdrawal request, ammount should be credit


next day before 1 pm (if no hollyday) otherwise it should credit
next of hollyday--manual

25. while withdrawing funds ,it should show withdrawable


ammount.

OOPs concept in Selenium Framework

1. Interface: WebDriver driver = new ChromeDriver();

In this statement WebDriver is nothing but interface in


selenium.

1. UPCASTING: WebDriver driver = new ChromeDriver();


above statement is nothing but UPCASTING in selenium.

2. INHERITANCE

We create a Base Class in the Framework to initialize


WebDriver interface, WebDriver waits, Property files etc., in the
Base Class.

We extend the Base Class in Tests Class. that is nothing


but Inheritance in Selenium Framework.

POLYMORPHISM

Combination of overloading and overriding is known as


Polymorphism.

3. METHOD OVERLOADING

We use implicit wait in Selenium. Implicit wait is an


example of overloading. In Implicit wait we use different time
stamps such as SECONDS, MINUTES, HOURS etc.,

A class having multiple methods with same name but


different parameters is called Method Overloading.

4. METHOD OVERRIDING

Declaring a method in child class which is already present


in the parent class is called Method Overriding.

Examples are get and navigate methods of different drivers


in Selenium.

5. ENCAPSULATION

All the POM classes in a framework are an example of


Encapsulation. In POM classes,

we declare the data members using @FindBy and


initialization of data members will be done using Constructor to
utilize those in methods.

Encapsulation is a mechanism of binding code and data


together in a single unit.

Encapsulation is the process of wrapping up code and data


together in a single unit. It is used to hide the data of a class
from another class.

Encapsulation can be achieved when you declare all


variables as private and a public method in a class to get the
values of the variable.

6. ABSTRACTION

In Page Object Model design pattern, we write locators


(such as id, name, xpath etc.,) in a Page Class.

We utilize these locators in pom class but we can’t see


these locators in the tests. Literally we hide the locators from
the tests.

Abstraction is the methodology of hiding the


implementation of internal details and showing the functionality
to the users.

Git configuration
Step 1: Login to your git account
Step 2: Click on + to add a git repository
Click on Create repository after filling the
details.
Move to the eclipse
Step 4: Right click on the project(Which we
wants to move to git repository) and say
Team the share project

Step 6: Click on Share project and check the


checkbox
Click on the create repository button and
then click on finish
Step 7: Right click on project and say Team
then click on add to index

Again go to team and say commit


Step 9: Provide the message and click on
commit or commit and push
Step 10: Right click on project ---- team ---
push branch master
Enter the url from the git page into the push
window
Enter git creds and click on finish and finish.

You might also like