Java Class Notes
Java Class Notes
Core Java
Basic terminologies
Classes
Methods
Variable
Constructor
Loops
OOPs concept:
Exception handling
Array
String Class
Collections
Selenium
Concept of Automation setup
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.
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.
To download java:
https://www.oracle.com/in/java/technologies/javase/javase-jdk8-downloads.html
https://www.eclipse.org/downloads/packages/release/oxygen
click on Eclipse 3A
Go to c:/Programfiles/Java
Go to bin folder
Eclipse setup:
To create package
java –version
Class :
Class is a plan through which we come to know what are the different logic we are
having in it.
Example:
package basic;
Shortcuts:
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
Example:
// byte = 1 byte or 8 bits maximum value = +127 and min value = -128
int i = 2147483647;
Note: The most common and preferred data type in numeric is integer.
              float f = 1.26565656f;
              //double = 8 bytes range = -3.4*10^308 to 3.4*10^308
double d = 2121215.3432476234782364723462378;
              boolean b = true;
              boolean bbs = false;
//char = 2 bytes
              char ch = 'a';
              char cc = '$';
Example
i=100;// initialization
int k = i/j;
System.out.println(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:
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;
//Object
//Static method
Example:
       }
public static void main(String[] args) {
      myFirstMethod();//calling of a method
addition();
}
}
2. By Classname.method name
For example:
Test t = new Test();
Example 1 :
t2.m5();
Output:
1. start jvm
4. Load Test.class file --- static method and variable memory allocation
7. JVM Shutdown.
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.
System.out.println(z);
     }
     public static void m2()
     {
           myFirstMethod();
     }
     // Creation of object
     //syntax-- Classname reference variable name = new Class name ();
     Test t = new Test();
t2.m5();
             myFirstMethod();
             Test.myFirstMethod();
Example:
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);
                        Types of Variables
Based on the location of defining a variable they are categorize in to 3 types:
1. 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.
or
ii. By Classname.Variable_name.
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:
       }
package methodsdiscussion;
myFirstMethod();
     System.out.println(i);
     int y= i+2;
}
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
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.
or
datatype variable_name;
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:
        int i = 50;
        //or
        int j;
}Output:
        int i = 50;
        //or
        int j;
System.out.println(i);
}
Example of static variable with respect to object:
int i = 50;
        //or
        int j;
System.out.println(i);
k = 30;
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.
            }
Example for
Use of this keyword in java
      int i = 50;
     //or
     int j;
            if(i<k)
            {
                int l = 10;
      System.out.println(l);
            }
            else
            {
                      int m = 20;
package Utility;
            int c = a+b;
            System.out.println(c);
      }
            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;
          b = true;
          c= 63;
return 50;
                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;
                int c = 0;
                System.out.println(c);
          }
return c;
          b = true;
          c = 8;
return 50;
boolean r = t.m3();
int f= t.m4()+3;
System.out.println(f);//6
          System.out.println(t.m4()+3);//6
    }
}
Constructors:
Definition:
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
3. Parameterized constructor
Rules:
public ConstructorBasics()
      {
           System.out.println("constructor is running");
      }
package Utility;
// to create constructor
//    or
//    public ConstructorBasics(int mm, int ss, int ee)
//    {
//           m = mm;
//           s = ss;
//           e = ee;
//   }
System.out.println(cb7.m);
}
Output: 10
     // to create constructor
     // Syntax -- public name_of_class()
//   {
//
//   }
     int m;
     int s;
     int e;
     public ConstructorBasics(int m) {
           System.out.println("one argument constructor");
     }
//   or
//   public ConstructorBasics(int mm, int ss, int ee)
//   {
//         m = mm;
//         s = ss;
//         e = ee;
//   }
}
Output:
one argument constructor
three argument constructor
two argument constructor
package Utility;
// to create constructor
      public ConstructorBasics(int m) {
            System.out.println("one 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;
//   }
Example 4:
package Utility;
// to create constructor
     public ConstructorBasics(int m) {
           this(10, true);
           System.out.println("one argument constructor");
     }
     public ConstructorBasics()
     {
           this(14);
//    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) {
     }
}
Output is :
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:
//Comparasion operator:
                if(w>z)
                {
                      System.out.println("if block is running");
                }
                else
                {
                       System.out.println("else 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.
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");
         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, 6, 9
//     Actions
//}
}
Output:
For loop
For loop
For loop
For loop
For loop
For loop
Example 2:
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++)
{
Output:
             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
                         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)
                   else
                   {
                          System.out.print(" ");
                   }
             }
             System.out.println();
             }
       }
Output:
*****
****
***
**
*
Ex 2
while(num != 0) {
        =tnu
           gm
            in
             dti i%10;
             sede
                svrd=r
                    evr;*1t0+d
                            gii
                 num=num/
                        10;
Output
It is used to break a particular loop and make the control out of the loop. The loop can also be
defined by label.
if(i==3)
break;
if (j == 2)
                                           break outerforloop;
                                 }
if(i==3)
continue;
Output:
i value is 0
i value is 1
i value is 2
i value is 4
i value is 5
Example 3:
if(i%2 == 0)
continue;
System.out.println(i);
Output:
                  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
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;
}
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.
}
package oopsconcept;
     }
}
package oopsconcept;
     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
Example:
package oopsconcept;
     int i =10;
     int j =60;
      }
}
package oopsconcept;
                                                                              //
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
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.
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
Example:
        public ParentConstructorClass2() {
              System.out.println(" zero arg Constructor of parent class");
public ChildConstructorClass()
        }
}
Output:
     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 ParentConstructorClass2(int a)
      {
            System.out.println("PArent one argument constructor");
      }
}
package oopsconcept;
public ChildConstructorClass()
      {
            super(20);
            System.out.println("Zero arg of child class constructor");
      }
      }
}
Output:
PArent one argument constructor
Zero arg of child class constructor
      public ParentConstructorClass2()
      {
            System.out.println("PArent's zero argument constructor");
      }
      public ChildConstructorClass(int i)
      {
      }
}
Polymorphism
Type of Polymorphism:
return 0;
     }
}
Example:
package polymorphism;
return 0;
package polymorphism;
     {
           System.out.println("m1 of Test 2 with no argument");
Output:
m1 of zero argument from Test2 class
m1 of zero argument from Test class
}
package polymorphism;
// 1 st object
// 2nd Object
     }
}
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.
Example:
package polymorphism;
package polymorphism;
     }
      public static void main(String[] args) {
            Parent p = new Child();
            p.marry();// Parent's 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
      int i = 20;
     public static void marry()
     {
           System.out.println("marry method of parent with 0 argument");
     }
}
package polymorphism;
       }
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
Access Modifiers
Defination: The keyword which tells the accessibility of a particular method,
variable or class.
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.
      public ParentConstructorClass2()
      {
            System.out.println("PArent's zero argument constructor");
      }
      public ChildConstructorClass()
      {
      }
}
class ChildConstructorClass {
     public ChildConstructorClass()
     {
     }
}
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;
package abstractdiscussion;
Example2:
package abstractdiscussion;
}
package abstractdiscussion;
}
package abstractdiscussion;
      @Override
      public void m5() {
            // TODO Auto-generated method stub
Example:
package abstractdiscussion;
public abstract class Test {
}
public abstract class Test2 extends Test {
     Test5 t5;
     Test4 t4;
     public Test()
     {
           t5 = new Test5();
           t4 = new Test4();
     }
     }
package abstractdiscussion;
package abstractdiscussion;
t2.login();
}
Output:
m2 method of Test4
m5 method of Test5
Note: here this method visible to every class provided the class in which it
got defined is public.
int i =10;
void m2()
     {
            Test t = new Test();
Example:
package oopsconcept;
public class A {
}
package methodsdiscussion;
import oopsconcept.A;
A a = new A();
           B b = new B();
           b.m1();
}
package oopsconcept;
public class C {
}
package methodsdiscussion;
        }
  }
 Example:
package interfaceDiscussion;
}
package interfaceDiscussion;
Example 2:
package interfaceDiscussion;
}
package interfaceDiscussion;
}
package interfaceDiscussion;
void m1();
void m2();
}
Note: here m1 and m2 method are by default public .
Multiple inheritance from interface
Example:
package interfaceDiscussion;
void m1();
void m2();
}
package interfaceDiscussion;
}
package interfaceDiscussion;
Example for calling method from Parent reference and child object.
package interfaceDiscussion;
Example:
package interfaceDiscussion;
}
Output: Static method from interface
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;
      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;
void m1();
void m2();
package interfaceDiscussion;
int i = 20;
 public void m1();
public void m2();
}
package interfaceDiscussion;
Example:
package interfaceDiscussion;
public interface Interface1 {
      int i =30;
}
package interfaceDiscussion;
int i = 20;
}
package interfaceDiscussion;
       }
       public void m2() {
     }
Example:
package encapsulation;
           return cust1bal;
     }
}
package encapsulation;
System.out.println(t.getBalance());
     }
}
Output: 10.0
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 {
           int i = 10;
           int j = 0;
           int k = i / j;
           System.out.println(k);
a. try-catch
Example:
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.
B. try-catch- finally
finally {
}
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;
}
     finally {
}
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)
Example:
package exceptionhandling;
     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 {
     }
}
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");
            }
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.
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) {
     }
     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
package arraydiscussion;
// initialization of array
           intarray[0] = 10;
           intarray[1] = 20;
           intarray[2] = 30;
           intarray[3] = 40;
           intarray[4] = 50;
}
        Output:
50
10
20
30
40
50
Note: If user tries to put more than the length of array elements then we
get ArrayIndexOutOfBoundException.
For example:
package arraydiscussion;
// 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;
}
Output:
10
20
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
     at arraydiscussion.ArrayTest.main(ArrayTest.java:24)
30
package arraydiscussion;
              // 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");
}
OutPut:
10
20
30
Array overflow
the size of array is :5
10
20
30
40
50
Example:
public static void main(String[] args) {
// initialization of array
            intarray[0] = 10;
            intarray[1] = 20;
            intarray[2] = 30;
            intarray[3] = 40;
            intarray[4] = 50;
Output:
10
20
30
40
50
// initialization of array
            intarray[0] = 10;
            intarray[1] = 20;
            intarray[2] = 30;
            intarray[3] = 40;
            intarray[4] = 50;
            for (int b : a) {
                   System.out.println(b);
            }
Output:
50
20
30
40
50
             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:
            // 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.
            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;
-127
package typecasting;
String s = "jsdhfsjdhfshdfjskdfshkdjfhs";
            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);
t.m1(z);
}
Output:
10
-127
-127
10
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;
A a = new A();
           a.m1();// m1 method of class A
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.
          if (ss==s)
          {
                   System.out.println("same object");
            }
            else
                             System.out.println("different object");
Note: If the opted char value is beyond the string range we would get
Exception
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):
Output: true
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:
String ss = "AbcdDDe";
Output: true
5. substring(int beginindex):
String s = "abcDDDE";
      String substr = s.substring(3);
       System.out.println(substr);
Output:
DDDE
Output: cDD
7. length():
This method returns the length of a particular string. Length is
actually maximum index +1.
For Example:
Output: 12
8. replace(char old, char new):
This method is used to replace the character with another
character.
String sss = "ababa";
Output: bbbbb
9. toLowerCase():
This method is used to convert the given string into lowercase.
For Example:
Output: ab1fdd
9. toUpperCase():
This method is used to convert the given string into uppercase.
For example:
Output: SHKJSDHA
10. trim():
This method is used to clear the space which is associated with
it as prefix and suffix.
For example:
Output: 6
String d = "abcdefghidef";
Output: true
14. toCharArray():
//toCharArray();
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
//isDigit()
char cc = '1';
boolean isdigitavailable = Character.isDigit(cc);
System.out.println(isdigitavailable);
Output: true
int z = 123;
}
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
Output:
Abcxy
cdwer
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;
           // 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(20);
             al.add(30);// this method will add the value to the
collection
             al.remove(0);// it will remove the value from the
arraylist
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);
      al3.add(100);
      al3.add(500);
      al3.addAll(al2);
      al3.addAll(al);// this method is to add all the elements from
al to al3.
System.out.println(al3);
import java.util.ArrayList;
import java.util.Arrays;
           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
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;
// list iterator
     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);
import java.util.ArrayList;
import java.util.HashSet;
import org.apache.poi.hpsf.Array;
          al.add("Ram");
          al.add("Shyam");
          al.add("Sita");
          al.add("geeta");
          al.add("Ravi");
          al.add("Monty");
System.out.println(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.
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.
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
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 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.
1. id
2. classname
3. name
4. xpath
5. text()
6. link text
7. partial link text.
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']
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();
           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 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.
WebElement admin =
driver.findElement(By.xpath("//*[@id='menu_admin_viewAdminModule']"));
System.out.println(attrivalue);
Output:
menu_admin_viewAdminModule
//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:
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
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
          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();
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.
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);
driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
For example:
driver.get("https://groww.in/");
          driver.manage().window().maximize();
         driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
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();
           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();
            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();
driver.findElement(By.xpath("//*[@id='enable-button']")).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='disable']")));
driver.findElement(By.xpath("//*[@id='enable-button']")).click();
wait.until(ExpectedConditions.alertIsPresent());
Thread.sleep(1000);
driver.switchTo().alert().accept();
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.until(ExpectedConditions.elementSelectionStateToBe(By.xpa
th("//*[@type='checkbox']"), true));
driver.findElement(By.xpath("//*[@id='checkbox']")).click();
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.
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
           //to get the path of the variable and let the java know
about it
           File src = new
File("C:\\Users\\A\\Desktop\\SampleTestData.xlsx");
           System.out.println(value);
    }
// to get the path of the variable and let the java know about it
           // sh1.getRow(5).getCell(0).setCellValue("TestData");
    //
// sh1.getRow(6).getCell(0).setCellValue("TestData1");
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(
            );
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
             if(type==CellType.NUMERIC)
             {
               double number =
sh1.getRow(row).getCell(column).getNumericCellValue();
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.
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;
    @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.
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;
    @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
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
     @AfterTest
     public void afterTest()
     {
          System.out.println("after test annotation from testng
class");
     }
     @AfterSuite
     @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;
     }
     @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.
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;
     @Test
     public void login() throws IOException
     {
           System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");
           Properties prop = new Properties();
prop.load(fis);
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();
Assert.assertEquals(loginerrormessage,
"Invalid credentialss", "Text not got matched
hence failing");
           driver.navigate().refresh();
           driver.get("https://meet.google.com/gvv-hnwq-vdx");
     }
    @Test
    public void testCase2()
    {
    }
}
prop.load(fis);
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();
          driver.navigate().refresh();
          driver.get("https://meet.google.com/gvv-hnwq-vdx");
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");
          Reporter.log("Login failed");
//        Assert.assertEquals("Login", "Dashboard");
          System.out.println("Dashboard");
          Assert.assertEquals(true, false);
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;
Reporter.log("Login failed");
          Reporter.log("Login failed");
//        Assert.assertEquals("Login", "Dashboard");
          System.out.println("Dashboard");
          Assert.assertEquals(true, false);
}
package testngdiscussion;
import org.testng.Reporter;
import org.testng.annotations.Test;
}
<?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 -->
<exclude name="testCase5"></exclude>
                     </methods>
                </class>
          </classes>
     </test> <!-- Test -->
</suite> <!-- Suite -->
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;
   @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
    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);
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;
    @Test
    public void testCase1() {
        Reporter.log("TC1 ", true);
System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");
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;
   @Test
   public void extraMethod() {
System.setProperty("webdriver.chrome.driver",
"E:\\Desktop\\VimanNagar\\Jan
21\\Downloaded\\chromedriver.exe");
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;
       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);
 </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 -->
 <classes>
 <class name="testngdiscussion.ParameterInTestNG"></class>
 </classes>
 </test> <!-- Test -->
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) {
    @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();
      }
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.
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.
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.
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:
validate - validate the project is correct and all necessary information is available
    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.
Keyword driven: If a particular word is used to detect a particular flow is called key word driven.
Maven Project
Step 1:
Step 3: Select the encircled type and click on the next button
https://maven.apache.org/plugins/maven-compiler-
plugin/usage.html
https://maven.apache.org/surefire/maven-surefire-
plugin/usage.html
https://mvnrepository.com/artifact/com.aventstack/extentrepor
ts
Modules present:
Total modules: 15 to 20
26. wishlist--add/remove
5. if you try to place order ,but you don't have fund in your
account then it should display insufficient fund msg
10. when we placed cover order (co) only Stop loss field enabled
12. after placing order ,in orders tab it will show Executed or
pending orders
20. at time of order placing, BSE Or NSE only one should enabled
2. INHERITANCE
POLYMORPHISM
3. METHOD OVERLOADING
4. METHOD OVERRIDING
5. ENCAPSULATION
6. ABSTRACTION
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