0% found this document useful (0 votes)
31 views143 pages

Core Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 143

Core Java

1. Java created By James Gosling - original released by 1995, sub microsystems - oracle

2. oops - object oriented programming language,

What is OOPS?

It allows users to create objects they want and create methods to handle those objects.

The basic concept of OOPs is to create objects, re-use them throughout the program, and manipulate
these objects to get results.

-- class

class is a collection of similar objects, it doesn't consume any space..

it contains objects, variables, methods, Constructor..

-methos is a block of code which only run insid a code,we can pass data using parameter.

--objects

An object can be defined as an instance of a class, and there can be multiple instances of a class in a
program.

which contains both the data and the function,it's a identity ,state, behaviour

-- Inheritance

 one class is allowed to inherit methods of another class.


 Code Reusability – reuse methods and variables from existing class,
 Single, multilevel, Hirerarchical, Hybrid.
--https://www.geeksforgeeks.org/inheritance-in-java/
Single :
Multilevel:

Hierarchical:

Hybrid:
Multiple:

multiple inheritance is not supported in java. Using interface.

Interface unable to create a object.

Why Multiple inheritance not supported in java

Only one class able to extend at compiler time it will not work.
Polymorphism: (static and Dynamic Binding)

Polymorphism we can perform single action in different ways.

polymorphism as the ability of a message to be displayed in more than one form.


Real life example of polymorphism: A person at the same time can have different characteristic. Like
a man at the same time is a father, a husband, an employee. So the same person posses different
behavior in different situations. This is called polymorphism.

Two types of polymorphism in Java: We can perform polymorphism in java by method overloading and
method overriding.

static and Dynamic Binding

Create same method with different argument in same class. – Static binding (Compile time
Polymorphism – Method Overloading)

Create same method with same argument in different class – Dynamic binding (Run time Polymorphism
– Method Overriding)
Method Overloading:

Same method name with different parameters.

class MultiplyFun {

// Method with 2 parameter


static int Multiply(int a, int b)
{
return a * b;
}

// Method with the same name but 2 double parameter


static double Multiply(double a, double b)
{
return a * b;
}
}

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

System.out.println(MultiplyFun.Multiply(2, 4));

System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
Method Overriding :

--same method name with same parameters

Encapsulation :

Data Hiding in Java is hiding the variables of a class from other classes. It can only be accessed
through the method of their current class. It hides the implementation details from the users. But
more than data hiding, it is meant for better management or grouping of related data.
It is used to bind up the data into a single unit called class. It provides the mechanism
which is known as data hiding. It is an important feature of OOPs. It prevents to access
data members from the outside of the class. It is also necessary from the security point
of view.

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their current class. Therefore, it is also
known as data hiding.
To achieve encapsulation in Java −
 Declare the variables of a class as private.
 Provide public setter and getter methods to modify and view the variables values
Java Inner Class :
Reverse String :

Reverse String without inbuilt Function in Java:

import java.util.Scanner;
class ReverseStringExample1
{
public static void main(String args[])
{
String s=”qwa”;
for(int i=s.length();i>0;--i) //i is the length of the string
{
System.out.print(s.charAt(i-1)); //printing the character at index i-1
}
}
}

Reverse words in java (Array and string for each word)


String originalStr = "arun kumar";

String words[] = originalStr.split("\\s");

// String words[] = {"arun","kumar"};

String reversedString = "";


for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}

// Displaying the string after reverse


System.out.print("Reversed string : " + reversedString);

Output : nura ramuk

ArrayList<String> strList = new ArrayList<String>(Arrays.asList(strSplit));


System.out.println(strList);
Collections.reverse(strList);

System.out.println(strList);

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


strList1.add("arun");
strList1.add("kumar");

String reversedString = "";

System.out.println(strList1.size());

for (int i = 0; i < strList1.size(); i++) {


String word = strList1.get(i);
String reverseWord = "";

for (int j = word.length() - 1; j >= 0; --j) {


reverseWord = reverseWord + word.charAt(j);
System.out.println(word + j);
System.out.println(word.charAt(j));

}
reversedString = reversedString + reverseWord + " ";
}
System.out.print("Reversed string : " + reversedString);

Array list reverse:


ArrayList<String> strList = new ArrayList<String>();
strList.add("arun");
strList.add("kumar");

Collections.reverse(strList);

System.out.println(strList);
Output :[kumar, arun]
String to ArrayList reverse:
String str = "Geeks";
// split string by no space
String[] strSplit = str.split("");

// Now convert string into ArrayList


ArrayList<String> strList = new
ArrayList<String>(Arrays.asList(strSplit));
Collections.reverse(strList);

System.out.println(strList);
Output: [s, k, e, e, G]

Integer Reverse

ArrayList aList = new ArrayList();


//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
Collections.reverse(aList);
System.out.println(aList);

Integer get length:


int cardnumber=12345;
String length = Integer.toString(cardnumber);
System.out.println(length.length());
User Input :

Try and Catch Exceptions:

https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/

1. Arithmetic Exception
Anything divided by zero – infinity
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

2. Array Index Out Of Bounds Exception:

--- array values have 3 index 0,1,2 if we have 3 4,5,6 th index getting error

int[] myNumbers = {1, 2, 3};


System.out.println(myNumbers[6]);

3. Null Pointer Exception:

4. File not Found Exception:


File is not available in mentioned location

5. String Index out of bound exception:


6. Number Format Exception:

Throw and Throws


1. Throw is used the throw exception explicitly inside a block of code.
2. If not declared throw syntax in catch block. Script will fail and it will not move to next
step.

Throws:
Throws is a keyword used in the method signature used to declare an exception which might
get thrown by the function while executing the code..
Try, Catch, Finally:
If try failed catch will execute and finally will be execute
If try, finally only is there – try failed or pass finally will be execute.

The finally block in java is used to put important codes such as clean up code e.g.
closing the file or closing the connection.

Break Statement:
It is used to terminate the loop,

Continue Statement:
continue statement is used when we want to skip a particular condition and continue the rest
execution.
Static and final Difference:
1. Static we can user it Variable, block, method, nested class.
2. Static keyword is used to memory consumption.
3. Static variable is called class variable.
4. Static method is called class method.
5. Without create an object we can call static method or variable. Main function have
static keyword so it will execute without object and JVM refers to static keyword for
execution.
Final Keyword:
Final variable cannot be Re initialized
We can’t reassign a value once declared a variable using final keyword
final int speedlimit=90

int speedlimit=100

Final Method:

If you make any method as final, you cannot override it.


Final class:

If you make any class as final, you cannot extend it.


Switch Statement:

 The switch statement is a multi-way branch statement


 If break statement removed output is “Invalid day”
Output: bh

Local and Global Variable:

 Variable can be declared inside the method – local variable


 Variable can be declared outside the method – global variable

Garbage Collection In java:

 Unreferenced objects can consume memory, java compile time automatically


remove the unwanted used memory in jvm, it’s a memory management
 Here allocated unreferenced objects

Integer i = new Integer(4);


i = null;

 We can declare a Gc method to call


// requesting JVM for running Garbage Collector
System.gc();

Constructor:
 A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created. It
can be used to set initial values for object attributes
 Constructor name must be same as class name,
 The purpose of constructor is to initialize the object,
 Once class loaded it will execute, no need to call

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {


Main myObj = new Main(); // Create an object of class Main
(This will call the constructor)

System.out.println(myObj.x); // Print the value of x

// Outputs 5

Types of Constructor:
Three Types – no argument, parameterized, default constructor,
1. Above is the no argument constructor
2. Below is the parameterized constructor
3. Default constructor - If we do not create any constructor, the Java compiler
automatically create a no-arg constructor during the execution of the program. This
constructor is called default constructor
4. A Java constructor cannot be abstract, static, final, constructor must not have a
return type.
Constructor Overloading :

Constructor Overriding is never possible in Java. This is because, Constructor looks like a
method but name should be as class name and no return value. Overriding means what we
have declared in Super class, that exactly we have to declare in Sub class it is
called Overriding.

Nested if:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Copy Constructor in Java


class Complex {

private double re, im;

// A normal parameterized constructor


public Complex(double re, double im) {
this.re = re;
this.im = im;
}

// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}

// Overriding the toString of Object class


@Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}

public class Main {

public static void main(String[] args) {


Complex c1 = new Complex(10, 15);

// Following involves a copy constructor call


Complex c2 = new Complex(c1);

// Note that following doesn't involve a copy constructor call as


// non-primitive variables are just references.
Complex c3 = c2;

System.out.println(c2); // toString() of c2 is called here


}
}
Abstract Class:
 Abstract it hiding internal details showing only
functionalities.
 Abstract method cannot have a body
 Other class extends abstract class, one abstract class
cannot extend another class,
 Could create a object call method for abstract class
method,
 Abstract class call only using extends for another class

Example of abstract method

abstract void printStatus();//no method body and abstract


sample program:

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Collections of Java:

The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).

HashMap:
Java HashMap class implements the Map interface which allows us to store key and value pair,
where keys should be unique. If you try to insert the duplicate key, it will replace the element of
the corresponding key. It is easy to perform operations using the key index like updation,
deletion, etc. HashMap class is found in the java.util package.
It allows us to store the null elements as well, but there should be only one null key. Since Java
5, it is denoted as HashMap<K,V>, where K stands for key and V for value.
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating
HashMap
map.put(1,"23"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"0.343");
map.put(4,"Grapes");
map.remove(3);
map.replace(2, "Apple","ravi");
map.replaceAll((k,v) -> "Ajay");

System.out.println(map.keySet());
System.out.println(map.values());
System.out.println(map.get(1));
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());

Uses in selenium

Array LIST:
Java ArrayList class uses a dynamic array for storing the elements. It is like an array,
but there is no size limit.

o Java ArrayList class can contain duplicate elements.

o Java ArrayList class maintains insertion order.

o Java ArrayList class is non synchronized.

o Implementation of arrayList is not synchronized is by default. It


means if a thread modifies it structurally and multiple threads
access it concurrently, it must be synchronized externally. It’s a
thread safe
o Java ArrayList allows random access because array works at the index basis.
o In ArrayList, manipulation is little bit slower than the LinkedList in Java because a
lot of shifting needs to occur if any element is removed from the array list.

//Array List
ArrayList<String> list=new ArrayList<String>();//Creating
arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
list.add("Grapes");
Collections.sort(list);
//Traversing list through the for-each loop
for(String fruit:list)
System.out.println(fruit);

//Printing the arraylist object


System.out.println(list);

//Traversing list through Iterator


Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move
to next

//Traversing list through for-each loop


for(String fruit:list)
System.out.println(fruit);

System.out.println("Returning element: "+list.get(1));//it will


return the 2nd element, because index starts from 0
list.set(1,"Dates");
list.remove("Banana");
list.remove(0);
//list.clear();

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


al2.add("Ravi");
al2.add("Hanumat");
//Adding new elements to arraylist
list.addAll(al2);
System.out.println("Updated list : "+list);
//Removing all the new elements from arraylist
list.removeAll(al2);
System.out.println("After invoking removeAll() method:
"+list);
Differenec Between SET and Arrya LIST:

S.No List Set

1. The list implementation allows us to add the The set implementation doesn't
same or duplicate elements. allow us to add the same or
duplicate elements.

2. The insertion order is maintained by the List. It doesn't maintain the insertion
order of elements.

3. List allows us to add any number of null values. Set allows us to add at least one
null value in it.

4. The List implementation classes are LinkedList The Set implementation classes
and ArrayList. are TreeSet, HashSet and
LinkedHashSet
Linked List

Same as for the array list

o Java LinkedList class can contain duplicate elements.

o Java LinkedList class maintains insertion order.

o Java LinkedList class is non synchronized.

o In Java LinkedList class, manipulation is fast because no shifting needs to occur.

o Java LinkedList class can be used as a list, stack or queue.


o

Static Keyword :

 Static is a memory management cannot create a object, we can access the method without
create object, public static main function we can access static variable and method with create
an object,
 Constructor will work once we create a object, static will execute once class is loaded at once,
static block we can use static variable, constructor will use non static variable,

Difference final and static : Final cannot reinitialize variable, but static can reinitialize.

JDK :

it’s a Environment to develop Java Application, and execute a java program, it’s platform independent
for jvm,jre,jdk..

JRE :

JRE IS Jre Consists JVM, JVM Run program for .class file Java byte code to execute line by line,
Interpreter is a line by line execution,

JDK = jre + development tools

JRE = jvm + library Files

Difference Between abstract vs interface:


6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

7) An abstract class can be extended using An interface can be implemented


keyword "extends". using keyword "implements".

Access Modifier:

 Private: private variable , methods within the class have only to access, unable to use other class
 Public: can access all methods , variables for another class
 Protected - The protected access modifier is accessible within package and
outside the package but through inheritance only.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){ B obj = new B();
obj.msg();
}
}
Output:Hello
Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.

Drop Down Select in Selenium:

Select fruits = new Select(driver.findElement(By.id("fruits")));


fruits.selectByVisibleText("Banana");
fruits.selectByIndex(1);

APACHE POI:

Read:
Write Excel:

Database Selenium:
//Load mysql jdbc driver
Class.forName("com.mysql.jdbc.Driver");

//Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl,username,password);

Statement stmt = con.createStatement();

ResultSet rs= stmt.executeQuery(query);

while (rs.next()){
String myName = rs.getString(1);

String myAge = rs.getString(2);


System. out.println(myName+" "+myAge);
}
// closing DB Connection
con.close();
}

Super Keyword in selenium:

Super keyword cannot main method getting error

class Animal { // Superclass (parent)

public void animalSound() {

System.out.println("The animal makes a sound");

class Dog extends Animal { // Subclass (child)

public void animalSound() {


super.animalSound(); // Call the superclass method

System.out.println("The dog says: bow wow");

public class Main {

public static void main(String args[]) {

Animal myDog = new Dog(); // Create a Dog object

myDog.animalSound(); // Call the method on the Dog object

This Keyword:

this keyword in Java is a reference variable that refers to the current object of a
method or a constructor.
The main purpose of using this keyword in Java is to remove the confusion
between class attributes and parameters that have same names.

1. this can be used to refer current class instance variable.

2. this() can be used to invoke current class constructor.

3. this can be passed as an argument in the method call.

4. this can be passed as argument in the constructor call.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

0 null 0.0
0 null 0.0

Solution of the above problem by this keyword


class Student{ int rollno;
String name; float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee; }
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){ Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display(); s2.display();
}}

Output:
111 ankit 5000
112 sumit 6000

Take ScreenShot:
File File = ((TakesScreenshot)driver)
.getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(File,
new File("image location"
+ FileName + ".jpeg"));
}

Checked Exception:
SQL Exception: Without declaration it will now work and it will show error in java
code and not able to run the java code so Need declare the exception like throws
SQLException. This is checked exception.
1) Checked: are the exceptions that are checked at compile time. If some code within
a method throws a checked exception, then the method must either handle the
exception or it must specify the exception using throws keyword.
For example, consider the following Java program that opens file at location “C:\test\
a.txt” and prints the first three lines of it. The program doesn’t compile, because the
function main() uses FileReader() and FileReader() throws a checked
exception FileNotFoundException. It also uses readLine() and close() methods, and
these methods also throw checked exception IOException
import java.io.*;

class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}
Unchecked Exception:

- We are not declaring any exception and java code will work without any issues and
code will work and execute.

Unchecked exceptions are not checked at compile time. It means if your program is
throwing an unchecked exception and even if you didn’t handle/declare that exception,
the program won’t give a compilation error. Most of the times these exception occurs
due to the bad data provided by user during the user-program interaction. It is up to the
programmer to judge the conditions in advance, that can cause such exceptions and
handle them appropriately. All Unchecked exceptions are direct sub classes
of RuntimeException class.

class Example {
public static void main(String args[])
{
int arr[] ={1,2,3,4,5};
/* My array has only 5 elements but we are trying to
* display the value of 8th element. It should throw
* ArrayIndexOutOfBoundsException
*/
System.out.println(arr[7]);
}
}

This code would also compile successfully since ArrayIndexOutOfBoundsException is


also an unchecked exception.
Note: It doesn’t mean that compiler is not checking these exceptions so we shouldn’t
handle them. In fact we should handle them more carefully. For e.g. In the above
example there should be a exception message to user that they are trying to display a
value which doesn’t exist in array so that user would be able to correct the issue.

Bug Life Cycle:


Bug Priority:

 Low, medium, High, Immediate.

Its priority of the bug to fix,

Severity:

Critical ,Major, Minor, Cosmetic

Priority Severity
 Defect Priority has defined the  Defect Severity is defined as the
order in which the developer degree of impact that a defect has
should resolve a defect on the operation of the product

Selenium

-- it’s a free open source automation testing framework,

-- multiple programming languages support java,c#, python,ruby etc

-- selenium IDE,Selenium Web driver is most popular one,selenium RC..

-- we can run a selenium web driver multiple browsers - chrome,firefiox,safri..

-- best one to run google chrome browser

-- multiple platforms os - windows , linux etc..

-- web Automation -selenium web driver, windows automation - winium is a selenim based.

-- UI SPy.exe to inspect the desktop application elements like name,id.. winium-desktop-driver.exe it will
connect a port we need exe..

-- Selenium can be used to automate functional tests and can be integrated with automation test tools
such as Maven, Jenkins, & Docker to achieve continuous testing.

It can also be integrated with tools such as TestNG, & JUnit for managing test cases and generating
reports.

-- pom (page object model) is a design pattern - 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.
Name of these methods should be given as per the task they are performing, i.e., web elements have
methods, test methods call - page and test

-- web element locators - name, id, cssSelector, linktext, xpath, partiallinktext,tagname,customize xpath

-- sikuli - GUI Automation Sikuli uses the technique of “Image Recognition” and “Control GUI” to interact
with elements of web pages and windows popups. In Sikuli, all the web elements are taken as images
and stored inside the project.

-- pyautoGUI - GUI Automation, it control keyboard, mouse..

-- extent & default tesNG Report.

-- Include and Exclude Maven xml, To

-- Scroll page - scrollby functions.

-- find element, find elements.

-- close, quit

-- maven repository – three types – local, central, server

-- xpath – bi directional vs css selector – forward directional,

-- send values without using send keys – other option is java script executor.

-- selenium Groups and wait condition, head less browser

-- drop down related

-- check box code if it’s checked or not.

-- all annotations are order wise.

-- how to get values text box field

-- selenium api have a demand

-- depends on methods

-- file config

Which of the following WebDriver methods counts the number of elements?


driver.findElements(By.id("search")).size()
Which method can be used as alternative of get method in WebDriver
to open URL in browser.
navigate().to("URL")
Locators selenium:

 ID, name, xpath, css selector, link text, partial link text, class name, tag name, customize xpath.

Xpath vs css selector:

xpath – bi directional , css selector – forward directional,

css is a faster performance , xpath is slower,

Xpath allows bidirectional flow which means the traversal can be both ways from parent to child and
child to parent as well. Css allows only one directional flow which means the traversal is from parent to
child only.

 Customized css can be created directly with the help of attributes id and class. For id,
the css expression is represented by # followed by the id [ #<<id expression>>. For class,
the css expression is represented by . followed by the class [.<<class expression>>].
Xpath does not have any feature like this.
 Xpath expression is represented by [//tagname[@attribute = 'value']. The css expression
is repression is represented by [tagname[attribute = 'value'].

Close and Quit:

Close is active browser only close.


Quit is closes all browsers opened

What is TestNG:

TestNG is automation Testing Framework (NG- Next Generation),JUNIT upgraded version is more
Features,
TestNG is one of the most widely used open source testing framework used in
automation testing suite.

Features :

 Support for multi-threaded testing.


 Supports annotations.
 TestNG uses more Java and OO features.

What is Selenium?
Selenium is a free (open-source) automated testing framework used
to validate web applications across different browsers and platforms.
You can use multiple programming languages like Java, C#, Python etc
to create Selenium Test Scripts.

Selenium web driver


Selenium WebDriver is a web framework that permits you to
execute cross-browser tests. This tool is used for automating web-
based application testing to verify that it performs expectedly.

Junit and TestNG:

Junit not available this annotation - @BeforeTest, @AfterTest, @BeforeSuite, @AfterSuite..

TestNG – have test suite using xml, its A test suite is a collection of test cases to execute set
of behaviour,
Junit have no option in xml, it have only in code

@RunWith(Suite.class)
@Suite.SuiteClasses({
SuiteTest1.class,
SuiteTest2.class,

})
Junit not support – dependency test like dependsonmethods, TestNG Supported

Test case execute multiple Times:

@Test(invocationCount = 5, threadPoolSize = 2)

public void test1(){

3. @Test(invocationCount = ?, threadPoolSize = ?)
The threadPoolSize attribute tells TestNG to create a thread pool to run the test
method via multiple threads. With thread pool, it will greatly decrease the running time
of the test method.

Example 3.1 – Start a thread pool, which contains 3 threads, and run the test method 3
times.

@Test(invocationCount = 3, threadPoolSize = 3)
public void testThreadPools() {

System.out.printf("Thread Id : %s%n", Thread.currentThread().getId());

Second EXAMPLE

@Test(invocationCount = 100, threadPoolSize = 5)


public void loadTest() {

System.out.printf("%n[START] Thread Id : %s is started!",


Thread.currentThread().getId());

WebDriver driver = new FirefoxDriver();


driver.get("http://yourwebsite.com");
//perform whatever actions, like login, submit form or navigation

System.out.printf("%n[END] Thread Id : %s",


Thread.currentThread().getId());

driver.quit();

}
}
Output – Above test will start a thread pool of 5, and send 100 URL requests to a
specified website.

[ThreadUtil] Starting executor timeOut:0ms workers:100 threadPoolSize:5

[START] Thread Id : 11 is started!


[START] Thread Id : 14 is started!
[START] Thread Id : 10 is started!
[START] Thread Id : 12 is started!
[START] Thread Id : 13 is started!
[END] Thread Id : 11
[START] Thread Id : 11 is started!
[END] Thread Id : 10
[START] Thread Id : 10 is started!
[END] Thread Id : 13
[START] Thread Id : 13 is started!
[END] Thread Id : 14
[START] Thread Id : 14 is started!
[END] Thread Id : 12
[START] Thread Id : 12 is started!
[END] Thread Id : 13

Object Repository XML:

Need dom4j jar file


<menu>
<mobiletesting>//a[text()='MOBILE TESTING']</mobiletesting>
<email> philadelphia-field-email</email>
<signup> philadelphia-field-submit </signup>
</menu>

File inputFile = new File("C:\\Users\\arunkumar.a\\eclipse-workspace\\New\\


src\\a_new\\object_repo.xml");

SAXReader saxReader = new SAXReader();


Document document = saxReader.read(inputFile);
String mobileTesting =
document.selectSingleNode("//menu/mobiletesting").getText();

String emailTextBox = document.selectSingleNode("//menu/email").getText();


String signUpButton = document.selectSingleNode("//menu/signup").getText();

System.out.println("mobileTesting"+mobileTesting);
System.out.println("emailTextBox"+emailTextBox);
System.out.println("signUpButton"+signUpButton);

Selenium Exceptions:

1. ElementNotVisibleException: In spite of the element being present in the DOM,


it is not visible (can not be interactive). For example, elements defined in HTML
with type =”hidden” <html
2. ElementNotSelectableException: An element is disabled (can not be
clicked/selected) in spite of being present in the DOM
3. NoSuchElementException: Webdriver is not able to determine the elements
during runtime, i.e., the FindBy method cannot find a particular component
4. NoSuchFrameException: Webdriver attempts to switch to an invalid frame,
which is unavailable
5. NoAlertPresentException: Webdriver is trying to switch to an invalid alert,
which is unavailable
6. NoSuchWindowException: Webdriver is trying to switch to an invalid window,
which is unavailable
7. StaleElementReferenceException: The referenced element is no longer
present on the DOM page (a reference to a component is now Stale). For example, the
item belongs to a different frame than the current one or the user has navigated away to
another page
8. SessionNotFoundException: Webdriver is acting immediately after ‘quitting’ the
browser
9. TimeoutException: The command did not complete in the specified time. For
example, the element didn’t display at the specified time. This is especially encountered
when working with waits
10. WebDriverException: Webdriver is acting immediately after ‘closing’ the
browser

Property File Access:


Properties prop = new Properties();
// load the properties file
prop.load(new FileInputStream("C:\\Users\\arunkumar.a\\eclipse-
workspace\\New\\src\\a_new\\property_file.properties"));
// get the property of "url" using getProperty()
System.out.println(prop.getProperty("url"));
System.out.println(prop.getProperty("name"));

Data Provider:

Includee and Exclude:

public class test


{
@Test
public void test1()
{
System.out.println("test1");
}
@Test
public void test3()
{
System.out.println("test3");
}

Groupsin testng:
Test Cases and Test Scenarios:

 Test case is covered all functionalities positive and negative


 Test Scenario 1: Check the Search Functionality
 Test Scenario 2: Check the Payments Functionality

GetwindowHandle() is return type string.

GetwindowHandles() is return type is set, will return handles for all tabs of a window. For example:- If
there are four tabs in a window is opened
OOPS Concept in Selenium:

 Web driver and Web Element is interface.. webdriver driver = new chromedriver();
Webdriver – Interface, Chromedriver - Class
 Inheritance - Property files, Excels.
Page object model – Page class have element ids and method using extends keyword to call in
main method.
 Encapsulation - @findby
 ABSTRACTION is a page object Model.
 Method Overloading – Implicit wait
 Method Overriding – driver.get, Navigate to

Selenium Return Type:

getWindowHandles()
It is used to handle multiple windows. It return type is Set. It will returns all handles
from all opened browsers by Selenium WebDriver

Window Handling in java:

Set – LinkedHashSet
Iterator - LinkedKeyIterator
Child return String
Parent return String

Windows id return
CDwindow-74994346B358FF4778B925BD3E44F094
CDwindow-11B8AD3443E5D944EF2E1D840F4FDC87

String parent=driver.getWindowHandle();

Set<String>s=driver.getWindowHandles();

// Now iterate using Iterator

Iterator<String> I1= s.iterator();

while(I1.hasNext())

String child_window=I1.next();

if(!parent.equals(child_window))

driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());

driver.close();

//switch to the parent window

driver.switchTo().window(parent);

Parallel & Cross browser Testing Execution using testing suite:

Run parallel = methods,class,tests..

parallel="methods"

parallel="test" - this two if any changes getting error ,those same

<suite name="Suite" parallel="methods" thread-count="2">


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

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="TestSuite" thread-count="2" parallel="tests" >

<test name="ChromeTest">

<parameter name="browser" value="Chrome" />

<classes>

<class name="a_new.Cross_Browser">

</class>

</classes>

</test>

<test name="FirefoxTest">

<parameter name="browser" value="Firefox" />

<classes>

<class name="a_new.Cross_Browser">

</class>
</classes>

</test>
</suite>

Code :

WebDriver driver;

@BeforeTest
@Parameters("browser")
public void setup(String browser) throws Exception{
//Check if parameter passed from TestNG is 'firefox'
if(browser.equalsIgnoreCase("firefox")){
//create firefox instance
System.setProperty("webdriver.gecko.driver", "C:\\Users\\
arunkumar.a\\eclipse-workspace\\New\\src\\a_new\\geckodriver.exe");
driver = new FirefoxDriver();
}
//Check if parameter passed as 'chrome'
else if(browser.equalsIgnoreCase("chrome")){
//set path to chromedriver.exe
System.setProperty("webdriver.chrome.driver","C:\\Users\\
arunkumar.a\\eclipse-workspace\\New\\src\\a_new\\chromedriver.exe");
//create chrome instance
driver = new ChromeDriver();
}
//Check if parameter passed as 'Edge'
else if(browser.equalsIgnoreCase("Edge")){
//set path to Edge.exe
System.setProperty("webdriver.edge.driver",".\\
MicrosoftWebDriver.exe");
//create Edge instance
driver = new EdgeDriver();
}
else{
//If no browser passed throw exception
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

@Test
public void testParameterWithXML() throws InterruptedException{
driver.get("http://demo.guru99.com/V4/");
//Find user name
WebElement userName = driver.findElement(By.name("uid"));
//Fill user name
userName.sendKeys("guru99");
//Find password
WebElement password = driver.findElement(By.name("password"));
//Fill password
password.sendKeys("guru99");
}

Text File Read in Java:

import java.io.*;
public class ReadFromFile2
{
public static void main(String[] args)throws Exception
{
// We need to provide file path as the parameter:
// double backquote is to avoid compiler interpret words
// like \test as \t (ie. as a escape sequence)
File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");

BufferedReader br = new BufferedReader(new FileReader(file));

String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Wait Alert is present :

wait.until(ExpectedConditions.alertIsPresent()) !=null);

Implicit wait Code:

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

Selenium 4.8.2

driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));

The Implicit Wait in Selenium is used to tell the web driver to wait for a certain
amount of time before it throws a "No Such Element Exception".
Explicit Wait:

Default value

The polling frequency- In case of Explicit wait, this polling frequency is by default 500
milliseconds.

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);


WebDriverWait wait = new WebDriverWait(driver,30);

WebDriverWait wait = new WebDriverWait(driver,30);


wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//
div[contains(text(),'COMPOSE')]")));

n order to declare explicit wait, one has to use “ExpectedConditions”. The following
Expected Conditions can be used in Explicit Wait.

 alertIsPresent()
 elementSelectionStateToBe()
 elementToBeClickable()
 elementToBeSelected()
 frameToBeAvaliableAndSwitchToIt()
 invisibilityOfTheElementLocated()
 invisibilityOfElementWithText()
 presenceOfAllElementsLocatedBy()
 presenceOfElementLocated()
 textToBePresentInElement()
 textToBePresentInElementLocated()
 textToBePresentInElementValue()
 titleIs()
 titleContains()
 visibilityOf()
 visibilityOfAllElements()
 visibilityOfAllElementsLocatedBy()
 visibilityOfElementLocated()

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"

IsDisplayed, isEnabled,is selected: (inspect element attributa we can findout enabled or disabled)

Isdisplayed- element is displayed or not.

Isenabled – button is enabled or not and if any element is hidden.

Is selected – dropdown and radio button and checkbox is selected or not

Boolean Display = driver.findElement(By.xpath("//*[@id='next']")).isDisplayed(); // true or false

if(searchBox.isEnabled())

System.out.println(“Search box is enabled. Return: ” +searchBox.isEnabled());


}

else {

System.out.println(“Search box is disabled. Return: ” +searchBox.isEnabled());

Hard vs Soft Asserts in Selenium


It is validate a test case pass or fail

Hard Assert – Hard Assert throws an AssertException immediately when an assert statement fails and
test suite continues with next @Test

The disadvantage of Hard Assert – It marks method as fail if assert condition gets failed and the
remaining statements inside the method will be aborted.

To overcome this we need to use Soft Assert. Let’s see what is Soft Assert.

Soft Assert – Soft Assert collects errors during @Test. Soft Assert does not throw an exception when an
assert fails and would continue with the next step after the assert statement.

If there is any exception and you want to throw it then you need to use assertAll() method as a last
statement in the @Test and test suite again continue with next @Test as it is.

We need to create an object to use Soft Assert which is not needed in Hard Assert.
Asset Equals:
String expectedTitle = "Free QA Automation Tools For Everyone";
String originalTitle = driver.getTitle();
Assert.assertEquals(originalTitle, expectedTitle)

Assert.assertNotEquals(ActualTitle, ExpectedTitle);

Assert.assertFalse(driver.findElement(By.cssSelector("//*[@id=\\\"navbar-
brand-centered\\\"]/ul/li[8]/a")).isSelected());

 Assert.assertEquals(boolean actual, boolean expected): Takes two boolean values


as input and validates if they are equal or not.
 Assert.assertTrue(condition): This method asserts if the condition is true or not. If
not, then the exception error is thrown.
 Assert.assertTrue(condition, message): Similar to the previous method with an
addition of message, which is shown on the console when the assertion fails along
with the exception.
 Assert.assertFalse(condition): This method asserts if the condition is false or not. If
not, then it throws an exception error.
 Assert.assertFalse(condition, message): Similar to the previous method but with an
addition of a message string which is shown on the console when the assertion fails,
i.e., the condition is true.

JavascriptExecutor:

// This will scroll down the page by 1000 pixel vertical


js.executeScript("window.scrollBy(0,1000)");
//This will scroll the page till the element is found
// will move top of the page – give the element
js.executeScript("arguments[0].scrollIntoView();", Element);
//This will scroll the web page till end.
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Scroll up
jse.executeScript("window.scrollBy(0,-250)");
ActionsChains:

Drag and drop

Mouse Right Click

Double click:
KeyBoard Event:

Mouse Hover:
Literals

Literal: Any constant value which can be assigned to the variable is


called as literal/constant.
// Here 100 is a constant/literal.
int x = 100;

Types of Literals
String Pool:

Java String.intern() Method

The String.intern() method puts the string in the String pool or refers to
another String object from the string pool having the same value. It returns a
string from the pool if the string pool already contains a string equal to the
String object.

public class StringPoolExample


{
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
String s4 = new String("Java").intern();
System.out.println((s1 == s2)+", String are equal."); // true
System.out.println((s1 == s3)+", String are not equal."); // false
System.out.println((s1 == s4)+", String are equal."); // true
}
}
Selenium cucumber

Feature File Name: userLogin.feature


Description: The user shall be able to login upon entering the correct username and
password in the correct fields. The user should be directed to the homepage if the
username and password entered are correct.
Keywords such as GIVEN, WHEN, and THEN used to write the test in Cucumber are
called Annotations.

 GIVEN user navigates to login page by opening Firefox


 WHEN user enters correct <username> AND <password> values
 THEN click login button

Mutable and Immutable variable:

Mutable – reinitialize the variable value.

Immutable - unable to change a variable value.

Static -mutable

mutable

Int a =10;

Int a=20;

Immutable

Final int a =10;


Immutable class

Final class declared cannot extends

Mutable class
Output:

JavaTpoint
Java Training
String break Reader:

import java.io.StringReader;
public class StringReaderExample {
public static void main(String[] args) throws Exception {
String srg = "Hello Java!! \nWelcome to Javatpoint.";
StringReader reader = new StringReader(srg);
int k=0;
while((k=reader.read())!=-1){
System.out.print((char)k);
}
}
}

Output:
Hello Java!!
Welcome to Javatpoint.

Difference Synchronized and Synchronized:

Synchronized access means it is thread-safe. So different threads can access the collection
concurrently without any problems, but it is probably a little bit slower depending on what you
are doing. Unsynchronized is the opposite. Not thread-safe, but a little bit faster.

Difference String Buffer and String Builder:

String Builder is fast;

No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread safe. It means two StringBuilder


threads can't call the methods of StringBuffer is non-
simultaneously. synchronized i.e.
not thread safe.
It means two
threads can call
the methods of
StringBuilder
simultaneously.

2) StringBuffer is less efficient than StringBuilder. StringBuilder


is more
efficient than
StringBuffer.

Array in java:
-Java array is an object which contains elements of a similar data type.(int string)

-Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.

- if values array is declared like (int a[] = new int[5]) add three array values but two
values are not added , It will as other two is zero

-Additionally, The elements of an array are stored in a contiguous memory location.

Contiguous memory allocation is basically a method in which a


single contiguous section/part of memory is allocated to a process or file needing it. ... We
can implement/achieve contiguous memory allocation by dividing the memory partitions into
fixed size partitions.

Types:
Single dimensional array

Multidimensional array
Same similarities for array and list

Similarities
o Array and ArrayList both are used for storing elements.

o Array and ArrayList both can store null values.

o They can have duplicate values.

o They do not preserve the order of elements.

Difference Array and array list

Single/ Multi- Array can be multi- ArrayList is always single-dimensional.


Dimensional dimensional.

Iterating We use for loop or for We use an iterator to iterate over


Values each loop to iterate over an ArrayList.
array.

Performance It performs fast in ArrayList is internally backed by the


comparison to ArrayList array in Java. The resize operation in
because of fixed size. ArrayList slows down the
performance.

Static/ Dynamic Array is static in size. ArrayList is dynamic in size.

Statically declared arrays are allocated memory at compile time and their size is fixed, i.e.,
cannot be changed later, String a[]=new String[5]; unable to change again

Array list Dynamically:

Data type size:


Desired Capabilities:

DesiredCapabilities handlSSLErr = DesiredCapabilities.chrome ()


handlSSLErr.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true)
WebDriver driver = new ChromeDriver (handlSSLErr);

Navigate commands:

driver.navigate().forward();
driver.navigate().to("www.javatpoint.com");
driver.navigate().back();
driver.navigate().refresh();

SOAP
SOAP stands for Simple Object Access Protocol
Soap return xml large data
Rest is return json only.

 SOAP can only work with  REST permits different data format such
XML format. As seen from as Plain text, HTML, XML, JSON, etc. But
SOAP messages, all data the most preferred format for
passed is in XML format. transferring data is JSON.

Java Heap Space:

Usually, this error is thrown when there is insufficient space to allocate an object in
the Java heap.

Primitive data Types:

Primitive Data Types: A primitive data type specify predefined, The size and type of variable
values are specified ,For example
Non Primitive data Types:

Difference Linked List and Array List

 Why manipulation is faster in linked list means

We have 10 values in list, insert new values inbetween easily added as container is said doubly
linked list..

 Why manipulation is slow in array list means

We have 10 values in list, insert new values inbetween in 3 not easily added as container ,
shifting one by one order 3 values move 4 , 4 values move 5, 5 th values move to 6, so it takes
time.
ArrayList LinkedList

1) ArrayList internally uses a dynamic LinkedList internally uses a doubly linked


array to store the elements. list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedList is faster than


is slow because it internally uses an ArrayList because it uses a doubly linked list, so
array. If any element is removed from no bit shifting is required in memory.
the array, all the bits are shifted in
memory.

3) An ArrayList class can act as a LinkedList class can act as a list and
list only because it implements List queue both because it implements List and
only. Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
mport java.util.*;
class TestArrayLinked{
public static void main(String args[]){

List<String> al=new ArrayList<String>();//creating arraylist


al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
List<String> al2=new LinkedList<String>();//creating linkedlist
al2.add("James");//adding object in linkedlist
al2.add("Serena");
al2.add("Swati");
al2.add("Junaid");

System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
}

Primitive Data Type Wrapper Class


Wrapper Class

Wrapper classes provide a


way to use primitive data
byte Byte
types (int, boolean, etc..)
as objects.
Sample:
short Short ArrayList<Integer> arr =
new ArrayList<>();

int Integer

long Long

float Float

double Double

boolean Boolean

char Character
public class Main {

public static void main(String[] args) {

Integer myInt = 5;

Double myDouble = 5.99;

Character myChar = 'A';

System.out.println(myInt.intValue());

System.out.println(myDouble.doubleValue());

System.out.println(myChar.charValue());

For example, the following methods are used to get the value associated with
the corresponding wrapper
object: intValue(), byteValue(), shortValue(), longValue(), floatValue
(), doubleValue(), charValue(), booleanValue().

Listeners:
package softwareTestingMaterial;

import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

public class RetryFailedTestCases implements IRetryAnalyzer {


private int retryCnt = 0;
//You could mentioned maxRetryCnt (Maximiun Retry Count) as per your requirement. Here I took 2,
If any failed testcases then it runs two times
private int maxRetryCnt = 2;

//This method will be called everytime a test fails. It will return TRUE if a test fails and need to be
retried, else it returns FALSE
public boolean retry(ITestResult result) {
if (retryCnt < maxRetryCnt) {
System.out.println("Retrying " + result.getName() + " again and the count is " + (retryCnt+1));
retryCnt++;
return true;
}
return false;
}
}

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;

public class RetryListenerClass implements IAnnotationTransformer {

@Override
public void transform(ITestAnnotation testannotation, Class testClass, Constructor
testConstructor, Method testMethod) {
IRetryAnalyzer retry = testannotation.getRetryAnalyzer();

if (retry == null) {
testannotation.setRetryAnalyzer(RetryFailedTestCases.class);
}

}
}

<listeners>
<listener class-name="softwareTestingMaterial.RetryListenerClass"/>
</listeners>

Rest Assured:
Post Response:
Put Response

DELETE:
LOG4j
Serialization rest asured:

Object to json convert

Deserialization
Difference between throw and throws in
Java
There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:

No. throw throws

1) Java throw keyword is used to explicitly Java throws keyword is used to declare
throw an exception. an exception.

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an instance. Throws is followed by class.


4) Throw is used within the method. Throws is used with the method
signature.

5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.

Integer to String Reverse:

String to Int

int decimalExample = Integer.parseInt("20");

Chrome Options:
Chrome options class is generally used in conjunction with Desired Capabilities for
customizing Chrome driver sessions. It helps you perform various operations like opening
Chrome in maximized mode, disable existing extensions, disable pop-ups, etc,

 start-maximized: Opens Chrome in maximize mode


 incognito: Opens Chrome in incognito mode
 headless: Opens Chrome in headless mode
 disable-extensions: Disables existing extensions on Chrome browser
 disable-popup-blocking: Disables pop-ups displayed on Chrome browser
 make-default-browser: Makes Chrome default browser
 version: Prints chrome browser version
 disable-infobars: Prevents Chrome from displaying the notification
'Chrome is being controlled by automated software

SSL certificates
// Create an object of desired capabilities class with Chrome driver
DesiredCapabilities SSLCertificate = DesiredCapabilities.chrome();
// Set the pre defined capability – ACCEPT_SSL_CERTS value to true
SSLCertificate.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
// Open a new instance of chrome driver with the desired capability
WebDriver driver = new ChromeDriver(SSLCertificate);

String Split using space:


String Split using COMMA:
String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
String[] words = strMain.split(", ");
for (String w:words)
{
System.out.println(w);
}

Output:

Alpha
Beta
Delta
Gamma
Sigma

Java Substring
Java Concatenation:
Split String Numberic character:

String Contains:

if input string is in lower case but contains upper case will


get
false
TestNG Annotations:

@BeforeMethod – driver Initialization


@AfterMethod – driver quit

 BeforeSuite - Report
 BeforeTest – Driver launch
 BeforeClass
 BeforeMethod
 Test Case
 AfterMethod
 AfterClass
 AfterTest – pass/fail
 AfterSuite – Driver Close/ ReportFlush

Method Overloading in selenium:


public void select(int i) {
this.list.selectByIndex(i);

public void select(String text) {

this.list.selectByVisibleText(text);

Rest Assured Selenium Java:

Post Code

Rest Assured Put:


Rest Assured Delete:

Rest Assured Get


Append In java:
Count Links

//Using tagname with anchor


List links = driver.findElements(By.tagName("a"));
System.out.println(“The number of links is “ + links.size());

Implicit Wait Explicit wait

The driver is asked to wait for a specific The driver is asked to wait till a certain
amount of time for the element to be
condition is satisfied.
available on the DOM of the page.

It affects the execution speed since each


It does not affect the execution speed since it is
step waits for this wait till it gets the
applicable to a particular element of the page
element it is looking for.

What is the difference between Implicit and Explicit wait?

Challenges faced in selenium:

Rest Assured JSON OBJECT


Token Authentication:
Reverse Integer:

Factorial:
int i,fact=1;
int number=5; //It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println(fact);

Reverse:

int input = 8769, last_digit, reverseValue =0;

while (input != 0) {

last_digit = input % 10;

reverseValue = reverseValue * 10 + last_digit;

input = input / 10;

System.out.println("reversedNum"+reverseValue);

Prime Number:
Prime number :3 5 7 , 41 is prime

Fibonacci:

Output :
01123456

Palindrome :
int r,sum=0,temp;
int n=454;//It is the number variable to be checked for palindrome

temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10; 45
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}

Second Largest
Get All links In selenium:

List<WebElement> allLinks = driver.findElements(By.tagName("a"));

//Traversing through the list and printing its text along with link
address
for(WebElement link:allLinks){
System.out.println(link.getText() + " - " +
link.getAttribute("href"));
}

Web Table in selenium Array List:

WebElement mytable =
driver.findElement(By.xpath("/html/body/table/tbody"));

List < WebElement > rows_table =


mytable.findElements(By.tagName("tr"));

//To calculate no of rows In table.


int rows_count = rows_table.size();
System.out.println("rows_count"+rows_count);
//Loop will execute till the last row of table.
for (int row = 0; row < rows_count; row++) {

//To locate columns(cells) of that specific row.


List < WebElement > Columns_row =
rows_table.get(row).findElements(By.tagName("td"));

//To calculate no of columns (cells). In that specific row.


int columns_count = Columns_row.size();

System.out.println("Number of cells In Row " + row + " are " +


columns_count);
//Loop will execute till the last cell of that specific row.

for (int column = 0; column < columns_count; column++) {


// To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value of row number " + row + " and
column number " + column + " Is " + celtext);
}
Words Count in java Duplicate words and all words:

String str= "Com mun ication com num 22 a b c a";


Map<String, Long> result = Arrays.stream(str.split("
")).map(String::toLowerCase).
collect(Collectors.groupingBy(s -> s, LinkedHashMap::new,
Collectors.counting()));
System.out.println(result);

{com=2, mun=1, ication=1, num=1, 22=1, a=2, b=1, c=1}

String str= "javaadd";


Map<String, Long> result =
Arrays.stream(str.split("")).map(String::toLowerCase).
collect(Collectors.groupingBy(s -> s, LinkedHashMap::new,
Collectors.counting()));
System.out.println(result);

{j=1, a=3, v=1, d=2}


Customize xpath

Xpath=//*[contains(text(),’Login’)]
//p[text()='Basic']/following-sibling::div/div/span[text()='BUY NOW']

Airtel.in site

Array to Set Convert and Array to Array List (Duplicate words removed for Set)
String[] array = {"C", "b", "a"};
Set<String> set = new HashSet<>(Arrays.asList(array));
Output:[B,C]

String[] geeks = { "Rahul", "Utkarsh", "Shubham", "Neelam" };

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


Linked Hashset Maintain insertion Order

String[] array = {"c", "b", "a","a","e"};

Set<String> str= new LinkedHashSet<>(Arrays.asList(array));

Output : [c,b,a,e]

Get Duplicate Words:

Swap variables
Git Commands:
git clone -b main https://gecgithub01.walmart.com/GlobalRecruitingSystem/SCRPApiAutomation.git

git status

git add .

git add "C:\Users\vn52k7b\Pictures\ApiAutomation\WelcomeMeApiClone\WelcomeMe-API_Tests\src\


util\externalApiUtils.js"

git commit -m "Work day changes"

git push -u origin main


git push -u origin QAL_Internal_Arun

git branch

git checkout <existing_branch>

git checkout -b <new_branch>

git pull repourl

Functional and Non Functional Testing:

Functional testing ensured the functions and features of the application working properly.

Smoke, sanity, Regression Testing, UI Testing also Functional

Non-Functional – Load Testing and stress, performance Testing.


Factory method

Multiple implementation have same interface

For ex: Interface OS. Implementation – windows, Android, IOS OS.


1. FactoryMain Class

Main function

OS obj = new Windows().


Obj.spec();
2. OS Interface
Public interface OS
{
Public void spec();
}
3. Android Class
Public class Android implement OS{
Public void spec() {
System.out.print(“android”)
}
4. Windows Class
Public class Windows implement OS {
Public void spec() {
System.out.print(“Windows”)
}
Factory object
API Response Code
200 Success Expected Result
503 – server busy
201 - new record created
401 UnAuthorized Access - Token Authentication Failed
400 - bad request- syntax error - request url and input syntax error
402 - account subscription expired
403 - forbidden - the server understands the request but refuses to authorize
it. you don't have permission
404 not found - The server has not found anything matching the Request-
URI. equest has been refused
500 Internal server error
502 Bad Gateway

https://www.restapitutorial.com/httpstatuscodes.html

Rewapping project

Java Map Interface


Selenium Cucumber:
Scenario: Successful Login with Valid Credentials
Given User is on Home Page
When User Navigate to LogIn Page
And User enters Credentials to LogIn
| Username | Password |
| testuser_1 | Test@153 |
| testuser_2 | Test@154 |
Then Message displayed Login Successfully
Step Definition
@When("^User enters Credentials to LogIn$")
public void user_enters_testuser_and_Test(DataTable
usercredentials) throws Throwable {

//Write the code to handle Data Table


for (Map<String, String> data :
usercredentials.asMaps(String.class, String.class)) {

driver.findElement(By.id("log")).sendKeys(data.get("Username"));

driver.findElement(By.id("pwd")).sendKeys(data.get("Password"));
driver.findElement(By.id("login")).click();
}

Test Runner
package cucumberTest;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
features = "src/test/Feature"
,glue={"src/main/stepDefinition"}
)

public class TestRunner {


}
Cucumber HTML Reports
For HTML reports, add html:target/cucumber-reports to
the @CucumberOptions plugin option.

@CucumberOptions(
features = "src/test/resources/functionalTests",
glue= {"stepDefinitions"},
plugin = { "pretty", "html:target/cucumber-reports" },
monochrome = true
)

Report Output Location

Maven Commands

1. mvn clean

This command cleans the maven project by deleting the target directory. The command
output relevant messages are shown below.

$ mvn clean

...

[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ maven-example-


jar ---

[INFO] Deleting
/Users/pankaj/Desktop/maven-examples/maven-example-jar/target

...

$
2. mvn compiler:compile

This command compiles the java source classes of the maven project.

$ mvn compiler:compile

...

[INFO] --- maven-compiler-plugin:3.8.1:compile (default-cli) @ maven-


example-jar ---

[INFO] Changes detected - recompiling the module!

[INFO] Compiling 1 source file to


/Users/pankaj/Desktop/maven-examples/maven-example-jar/target/classes

...

5. mvn install

This command builds the maven project and installs the project files (JAR, WAR,
pom.xml, etc) to the local repository.

12. mvn test

This command is used to run the test cases of the project using the maven-surefire-
plugin.

Hashmap and Hashtable

HashMap Hashtable

1) HashMap is non synchronized. It is not- Hashtable


thread safe and can't be shared between is synchronized. It is
many threads without proper thread-safe and can be
synchronization code. shared with many threads.

2) HashMap allows one null key and Hashtable doesn't allow


multiple null values. any null key or value.

3) HashMap is a new class introduced in Hashtable is a legacy


JDK 1.2. class.

4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as Hashtable is internally


synchronized by calling this code synchronized and can't be
Map m = unsynchronized.
Collections.synchronizedMap(hashMap);

6) HashMap is traversed by Iterator. Hashtable is traversed by


Enumerator and
Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hashtable


is not fail-fast.

8) HashMap inherits AbstractMap class. Hashtable


inherits Dictionary class.

Abstraction

Abstraction is a process of hiding the implementation details and


showing only functionality to the user. Another way, it shows only
essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message.

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can
have abstract and non-abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the
body of the method.
Abstract and Interface:

Interface

Abstract class Interface

1) Abstract class can have abstract Interface can have only


and non-abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support Interface supports multiple


multiple inheritance. inheritance.

3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to


declare abstract class. declare interface.

6) An abstract class can extend An interface can extend another Java


another Java class and implement interface only.
multiple Java interfaces.

7) An abstract class can be An interface can be implemented using


extended using keyword "extends". keyword "implements".

8) A Java abstract class can have Members of a Java interface are public by
class members like private, protected, default.
etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
where local and global variable are stored in java:

Global variables are stored in the data segment of memory(Heap). Local variables
are stored in a stack in memory. We cannot declare many variables with the same
name. We can declare various variables with the same name but in other functions.

What is Stack Memory?


Stack in java is a section of memory which contains methods, local variables, and
reference variables. Stack memory is always referenced in Last-In-First-Out order.
Local variables are created in the stack.

What is Heap Memory?


Heap is a section of memory which contains Objects and may also contain
reference variables. Instance variables are created in

Memory Allocation in Java


Memory Allocation in Java is the process in which the virtual memory sections are
set aside in a program for storing the variables and instances of structures and
classes. However, the memory isn’t allocated to an object at declaration but only a
reference is created. For the memory allocation of the object, new() method is
used, so the object is always allocated memory on the heap.

Testing Life Cycle (STLC)


Automation Life cycle:

1. Determining the Scope of Test Automation


This stage Refers to the decisions which are taken for the feasibility study of the automation testing process. A

proposal should be made, which will contain the following evaluations:

Application modules that can be automated need to be identified from the ones which cannot. Important tafactors

such as the cost of the automation tool, the size of the testing team and expertise related to the automation
process need to be identified and considered. Feasibility checks should be performed before starting automation

testing, these include test case automation feasibility and AUT automation feasibility checks.

Upcasting and downcasting in java

A process of converting one data type to another is known


as Typecasting and Upcasting and Downcasting is the type of object
typecasting. In Java, the object can also be typecasted like the
datatypes. Parent and Child objects are two types of objects. So, there are
two types of typecasting possible for an object, i.e., Parent to
Child and Child to Parent or can say Upcasting and Downcasting.

In Java, the object can also be typecasted like the


datatypes. Parent and Child objects are two types of objects. So, there are
two types of typecasting possible for an object, i.e., Parent to
Child and Child to Parent or can say Upcasting and Downcasting.

Typecasting is used to ensure whether variables are correctly processed by


a function or not. In Upcasting and Downcasting, we typecast a child
object to a parent object and a parent object to a child
object simultaneously. We can perform Upcasting implicitly or explicitly, but
downcasting cannot be implicitly possible.
1) Upcasting
Upcasting is a type of object typecasting in which a child object is
typecasted to a parent class object. By using the Upcasting, we can easily
access the variables and methods of the parent class to the child class. Here,
we don't access all the variables and the method. We access only some
specified variables and methods of the child class. Upcasting is also known
as Generalization and Widening.

UpcastingExample.java

1. class Parent{
2. void PrintData() {
3. System.out.println("method of parent class");
4. }
5. }
6.
7. class Child extends Parent {
8. void PrintData() {
9. System.out.println("method of child class");
10. }
11. }
12.class UpcastingExample{
13. public static void main(String args[]) {
14.
15. Parent obj1 = (Parent) new Child();
16. Parent obj2 = (Parent) new Child();
17. obj1.PrintData();
18. obj2.PrintData();
19. }
20.}

Output:
2) Downcasting
Upcasting is another type of object typecasting. In Upcasting, we assign a
parent class reference object to the child class. In Java, we cannot assign a
parent class reference object to the child class, but if we perform
downcasting, we will not get any compile-time error. However, when we run
it, it throws the "ClassCastException". Now the point is if downcasting is
not possible in Java, then why is it allowed by the compiler? In Java, some
scenarios allow us to perform downcasting. Here, the subclass object is
referred by the parent class.

Below is an example of downcasting in which both the valid and the invalid
scenarios are explained:

DowncastingExample.java

1. //Parent class
2. class Parent {
3. String name;
4.
5. // A method which prints the data of the parent class
6. void showMessage()
7. {
8. System.out.println("Parent method is called");
9. }
10.}
11.
12.// Child class
13. class Child extends Parent {
14. int age;
15.
16. // Performing overriding
17. @Override
18. void showMessage()
19. {
20. System.out.println("Child method is called");
21. }
22.}
23.
24.public class Downcasting{
25.
26. public static void main(String[] args)
27. {
28. Parent p = new Child();
29. p.name = "Shubham";
30.
31. // Performing Downcasting Implicitly
32. //Child c = new Parent(); // it gives compile-time error
33.
34. // Performing Downcasting Explicitly
35. Child c = (Child)p;
36.
37. c.age = 18;
38. System.out.println(c.name);
39. System.out.println(c.age);
40. c.showMessage();
41. }
42.}

Output:
Difference between Upcasting and Downcasting
These are the following differences between Upcasting and Downcasting:

S.N Upcasting Downcasting


o

1. A child object is typecasted to a The reference of the parent class object is


parent object. passed to the child class.

2. We can perform Upcasting Implicitly Downcasting is not possible.


implicitly or explicitly.

3. In the child class, we can access The methods and variables of both the
the methods and variables of the classes(parent and child) can be
parent class. accessed.

4. We can access some specified All the methods and variables of both
methods of the child class. classes can be accessed by performing
downcasting.

5. Parent p = new Parent() Parent p = new Child()


Child c = (Child)p;

WebDriver driver = new ChromeDriver(); -> Why is WebDriver used?


//WebDriver – Interface
//ChromeDriver – Class

Types of TestNG Listeners


Listeners are implemented in code via interfaces to modify TestNG behaviour. Listed
below are the most commonly used TestNG listeners:

 IAnnotationTransformer
 IExecutionListener
 IHookable
 IInvokedMethodListener
 IMethodInterceptor
 IReporter
 ISuiteListener
 ITestListener

 IExecutionListener: As the name suggests, it monitors the beginning and end of


TestNG execution. This listener is mostly used to start/stop the server while
starting or ending code execution. It may also be used to inform respective
stakeholders via email that execution shall start or when it ends. It has two
methods:

1.
1. onExecutionStart() – invoked before TestNG starts executing the suites
2. onExecutionFinish() – invoked after all TestNG suites have finished
execution
 ITestListener: This is the most frequently used TestNG listener. ITestListener is
an interface implemented in the class , and that class overrides the ITestListener
defined methods. The ITestListener listens to the desired events and executes
the methods accordingly. It contains the following methods:

1. onStart(): invoked after test class is instantiated and before execution of any
testNG method.
2. onTestSuccess(): invoked on the success of a test
3. onTestFailure(): invoked on the failure of a test
4. onTestSkipped(): invoked when a test is skipped
5. onTestFailedButWithinSuccessPercentage(): invoked whenever a method
fails but within the defined success percentage
6. onFinish(): invoked after all tests of a class are executedThe above-mentioned
methods use the parameters ITestContext and ITestResult. The ITestContext is a
class that contains information about the test run. The ITestResult is an interface that
defines the result of the test.

What is meant by adhoc testing?


Performing random testing without any plan is known as Ad Hoc Testing. It is also
referred to as Random Testing or Monkey Testing.

Word count in java

String str = "12 321";


// String str = "arunn";
HashMap<Character, Integer> hmap = new HashMap<Character, Integer>();
str= str.replaceAll("\\s+", "");
for(int i=str.length()-1;i>=0;i--){

if(hmap.containsKey(str.charAt(i))){
int count = hmap.get(str.charAt(i));
hmap.put(str.charAt(i), ++count);
}
else {
hmap.put(str.charAt(i), 1);
}
}
System.out.println(hmap);

{1=2, 2=2, 3=1}

String str = "WWEERRWE";


char[] ch = str.toCharArray();
for(int i =0;i<ch.length;i++){
int count = 1;
while(i+1<str.length() && ch[i] == ch[i+1]){
i++;
count++;
}
System.out.println(ch[i]+" : "+count);
}

W : 2
E : 2
R : 2
W : 1
E : 1

Removing first and last character:

String str = "arun";


StringBuilder sb = new StringBuilder(str);

// Removing the last character


// of a string
sb.deleteCharAt(str.length() - 1);

// Removing the first character


// of a string
sb.deleteCharAt(0);

System.out.println(sb);

Output : ru
Select Dropdown without using select class:

public static void main(String[] args) {


System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\
Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/tutor_connect/index.php";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// getting the list of elements with the xpath
List<WebElement> opt =
driver.findElements(By.xpath("//select[@name=’selType’]//option"));
int s = opt.size();
// Iterating through the list selecting the desired option
for( int j = 0; j< opt.size();j++){
// if the option is By Subject click that option
if( opt.get(j).getText().equals("By Subject")){
opt.get(j).click();
break;
}
}
driver.quit();
}

Select Dropdown using select class:


Select se = new
Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']")));

// Select the option using the visible text


se.selectByVisibleText("White");

se.selectByIndex(1);
se.selectByIndex(2);

As we can see, this method returns all the options of the dropdown as a list
of WebElement. The following code snippet shows how we can get all the
options of the dropdown on the page "https://demoqa.com/select-
menu":

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

// Get all the options of the dropdown


List<WebElement> options = select.getOptions();
Using this method, we can retrieve all the options of a dropdown (be it
single-select or multi-select ).
getFirstSelectedOption()
This method returns the first selected option of the dropdown. If it is a single-
select dropdown, this method will return the selected value of
the dropdown, and if it is a multi-select dropdown, this method will return the
first selected value of the dropdown. It possesses the following syntax:

getFirstSelectedOption(): WebElement
As we can see, this method returns a WebElement. The following code
snippet shows how we can get the first selected option of the dropdown on
the page "https://demoqa.com/select-menu":

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

// Get the first selected option of the dropdown


WebElement firstSelectedOption = select.getFirstSelectedOption();
Using this method, we can retrieve the first selected option of a dropdown
(be it single-select or multi-select ).

getAllSelectedOptions()
This method returns all the selected options of the dropdown. If it is a single-
select dropdown, this method will return the only selected value of
the dropdown, and if it is a multi-select dropdown, this method will return all
the selected values of the dropdown. It possesses the following syntax:

getAllSelectedOptions():List<WebElement>
As we can see, this method returns a list of WebElements. The following
code snippet shows how we can get all the selected options of
the dropdown on the page "https://demoqa.com/select-menu":

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

// Get all the selected option of the dropdown


List<WebElement> selectedOptions = select.getAllSelectedOptions();
Using this method, we can retrieve all the selected options of a dropdown
(be it single-select or multi-select ).

How to deselect a value from a dropdown in Selenium?


 deselectAll()
 deselectByIndex()
 deselectByValue()
 deselectByVisibleText()

Select select = new


Select(driver.findElement(By.id("oldSelectMenu")));

//Deselect all the options


select.deselectAll();

Select select = new


Select(driver.findElement(By.id("oldSelectMenu")));

//Deselect first value by index


select.deselectByIndex(1);

Select select = new


Select(driver.findElement(By.id("oldSelectMenu")));

//Deselect option with value "6"


select.deselectByValue("6");

Select select = new


Select(driver.findElement(By.id("oldSelectMenu")));

//Deselect option with text "White"


select.deselectByVisibleText("White");

select multiselect dropdown

Select oSel = new Select(driver.findElement(By.xpath(//*[@id='cars']);

if(oSel.isMultiple()){
//Selecting multiple values by index
oSel.selectByIndex(1);
oSel.selectByIndex(2);

//Or selecting by values


oSel.selectByValue("volvo");
oSel.selectByValue("audi");

//Or selecting by visible text


oSel.selectByVisibleText("Volvo");
oSel.selectByVisibleText("Opel");
}

Equals and == difference

String s1=new String("hello");


String s2=new String("hello");

Here we have created two strings s1 and s2 now will use the == and equals () method to compare
these two String to check whether they are equal or not.

First, we use the equality operator == for comparison which only returns true if both reference
variables are pointing to the same object.

if(s1==s2) {
System.out.printlln("s1==s2 is TRUE");
} else{
System.out.println("s1==s2 is FALSE");
}

The output of this comparison is FALSE because we have created two objects which have a
different location in the heap so == compare their reference or address location and return false.
Now if we use the equals method to check their equivalence what will be the output

if(s1.equals(s2)) {
System.out.println("s1.equals(s2) is TRUE");
} else {
System.out.println("s1.equals(s2) is FALSE");
}

The output of this comparison is TRUE because of java.lang.String class has already
overridden the equals() method of Object class and check that contents are the same or not
because both have the same value hello so they are equal according to String
class equals() method.

A picture is worth thousands of words and here is a picture that explains whatever I have said in the
above paragraph about equals() vs == operator in the case of String in Java:

String strObject = new String("Java");


and

String strLiteral = "Java";

File upload Rest assured:


Duplicate removed and unique Hashmap key and value:

Map<Object, Object> map = new HashMap<Object, Object>();


map.put(1,5);
map.put(3,6);
map.put(2,7);
map.put(1,5);

Set<Object> key = new HashSet<Object>(map.keySet());

Set<Object> value = new HashSet<Object>(map.values());

//Duplicate key and values are removd


System.out.println(key);
System.out.println(value);

Output:

[1, 2, 3]
[5, 6, 7]

Enlisted below is the basic difference between the navigate() and get()
method and this is frequently asked in Selenium Interviews.
 get() method will wait till the page is completely loaded in the
browser while navigate() would not.
 navigate() method essentially returns a Navigate Interface which
allows a user to traverse back, forward, or refresh pages as you
would do in an actual browser window, while this functionality is not
possible with the get() method

sl.n get() navigate()


o.

1 It is responsible for loading the page and It is only responsible for redirecting the
waits until the page has finished loading. page and then returning immediately.

2 It cannot track the history of the browser. It tracks the browser history and can
perform back and forth in the browser.

Selenium 3 Architecture
Selenium 3 architecture supports JSON Wire Protocol, here JSON stands for
JavaScript Object Notation. Selenium 4 does not include the JSON Wire
Protocol and that’s the main difference between selenium 4 and Selenium 3.

JSON Wire Protocol transfers the information from the client to the server
over HTTP, here HTTP stands for Hypertext Transfer Protocol, in this, a
selenium request is sent from a selenium client, the request is received by
the JSON Wire Protocol over HTTP, and secured by the browser Driver, after
that a response returned by the server and received by the client.

Below the diagram is a graphical representation of Selenium 3 Architecture:


Selenium 4 Architecture
In Selenium 4 there is direct communication between the client and server.
In selenium 4 client has 2 parts first is Selenium Client & the other one is
WebDriver Language Bindings while Browser Drivers are the server.

In selenium 4, Selenium Client sends out a request to perform a command.


The WebDriver Language Bindings is a code library that is mainly designed
to drive actions. Browser Drivers receive the request sent by the client and
then return a response after an automation Test Script executes on the Web
Browser.

The Selenium Client and WebDriver Language Bindings are an important part
of the architecture where each language has its own unique bindings.
Bindings mean that the same commands can be used by different languages.
for example, a command written in java language has also been written in
other languages like c#, Python, Ruby, etc.

When we talk about Browser Drivers and Web Browsers, WebDriver drives
each and every browser using the browser’s built-in automation support. A
Browser Driver such as Chrome Driver controls the Chrome browser.
Selenium 4 is different from Selenium 3, As In Selenium 4 ChromeDriver and
EdgeDriver extend ChromiumDriver while RemoteWebDriver is the parent to
ChromiumDriver.

What is selenium W3C?

In Selenium 4, WebDriver W3C Protocol replaces the older JSON Wire protocol. It
essentially means that we no longer need to encode and decode the API request using
the W3C protocol, and the tests can directly communicate with the web browser.
Count of butttons, Radio

List<WebElement> li1 = driver.findElements(By.xpath("//button"));

List<WebElement> li2 =
driver.findElements(By.xpath("//input[@type='radio']"));

List<WebElement> li3 =
driver.findElements(By.xpath("//input[@type='checkbox']"));

List<WebElement> li4 = driver.findElements(By.xpath("//select"));


//Dropdown

List<WebElement> li5 =
driver.findElements(By.xpath("//input[@type='text']"));

List<WebElement> li6 = driver.findElements(By.xpath("//textarea")); //


large text box

List<WebElement> li7 =
driver.findElements(By.xpath("//input[@type='password']"));
System.out.println(li1.size());
System.out.println(li2.size());
System.out.println(li3.size());
System.out.println(li4.size());
System.out.println(li5.size());
System.out.println(li6.size());
System.out.println(li7.size());

List<WebElement> allLinks = driver.findElements(By.tagName("a"));

//Traversing through the list and printing its text along with link
address
for(WebElement link:allLinks){
System.out.println(link.getText() + " - " +
link.getAttribute("href"));
}
Main Method Overload in Java:

// Main Method Overloading but can't override and also Normally static
method can't override )

It will execute first method compiler will take

public static void main(String[] args) {

System.out.println("one");
}

public static void main(String args) {

System.out.println("one");
}

Output: one

Disabled Text Box Automate it will pass the value: (manually will not work)

driver.get("https://selectorshub.com/xpath-practice-page/");

//Send values to Disabled Text box


JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.querySelector(\"input[placeholder='Enter
Last name']\").disabled=false");

driver.findElement(By.xpath("//input[@placeholder='Enter Last
name']")).sendKeys("selenium");
Buttons, links, counts:

List<WebElement> li1 = driver.findElements(By.xpath("//button"));


List<WebElement> li2 =
driver.findElements(By.xpath("//input[@type='radio']"));
List<WebElement> li3 =
driver.findElements(By.xpath("//input[@type='checkbox']"));
List<WebElement> li4 = driver.findElements(By.xpath("//select"));
//Dropdown
List<WebElement> li5 =
driver.findElements(By.xpath("//input[@type='text']")); // textbox
List<WebElement> li6 = driver.findElements(By.xpath("//textarea")); //
large text box
List<WebElement> li7 =
driver.findElements(By.xpath("//input[@type='password']"));
System.out.println(li1.size());
System.out.println(li2.size());

File upload selenium:

driver.get("https://the-internet.herokuapp.com/upload");
//we want to import selenium-snapshot file.
driver.findElement(By.id("file-
upload")).sendKeys("selenium-snapshot.jpg");
driver.findElement(By.id("file-submit")).submit();
if(driver.getPageSource().contains("File
Uploaded!")) {
System.out.println("file uploaded");
}
else{
System.out.println("file not
uploaded");
}

<input id="file-upload"

type="file" name="file">
Alert and popup Handling:

1) Simple Alert
The simple alert class in Selenium displays some information or warning on the
screen.

2) Prompt Alert
This Prompt Alert asks some input from the user and Selenium webdriver can enter
the text using sendkeys(” input…. “).

3) Confirmation Alert
This confirmation alert asks permission to do some type of operation.
1) void dismiss() // To click on the ‘Cancel’ button of the alert.
driver.switchTo().alert().dismiss();

2) void accept()// To click on the ‘OK’ button of the alert.


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

3) String getText() // To capture the alert message.


driver.switchTo().alert().getText();

RegEx TestNG
https://www.javatpoint.com/how-to-use-regex-in-testng

1. public class test


2. {
3. @Test
4. public void WebLoginCarLoan()
5. {
6. System.out.println("WebLoginCarLoan");
7. }
8. @Test
9. public void MobileLoginCarLoan()
10. {
11. System.out.println("MobileLoginCarLoan");
12. }
13. @Test
14. public void MobileLoginPersonalLoan()
15. {
16. System.out.println("MobileLoginPersonalLoan");
17. }
18. @Test
19. public void MobileLoginHomeLoan()
20. {
21. System.out.println("MobileLoginHomeLoan");
22. }
23. @Test
24. public void LoginAPICarLoan()
25. {
26. System.out.println("LoginAPICarLoan");
27. }
28. }
29.

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


2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
3. <suite name="test_suite">
4. <test name="test">
5. <classes>
6. <class name="com.javatpoint.test">
7. <methods>
8. <include name="Mobile.*"/>
9. </methods>
10. </class>
11. </classes>
12. </test> <!-- Test -->
13. </suite> <!-- Suite -->

Lowercase and upper case in java

String input = "javaIbEst";


System.out.println("Lower case string is : " + input);

ArrayList<Character> s = new ArrayList<Character>();


ArrayList<Character> s1 = new ArrayList<Character>();
ArrayList<Character> s2 = new ArrayList<Character>();
char strArr[] = input.toCharArray();
for (int i = 0; i < strArr.length; i++) {
// here is the actual logic
if (strArr[i] >= 'a' && strArr[i] <= 'z') {
// strArr[i] = (char) ((int) strArr[i] - 32);
s1.add(strArr[i]);

}
else{
// strArr[i] = (char) ((int) strArr[i] + 32);
System.out.println(strArr[i] +"no");
s2.add(strArr[i]);

}
}
System.out.print("Upper case string is : ");
// print the string array
for (int i = 0; i < strArr.length; i++) {
System.out.print(strArr[i]);
}
// System.out.print(s);
System.out.print(s1);
System.out.print(s2);

Remove Special Chars

public class RemoveSpecialCharacterExample3


{
public static void main(String[] args)
{
//declare a string having special characters
String str="Pr!ogr#am%m*in&g Lan?#guag(e";
String resultStr="";
//loop execute till the length of the string
for (int i=0;i<str.length();i++)
{
//comparing alphabets with their corresponding ASCII value
if (str.charAt(i)>64 && str.charAt(i)<=122) //returns true if both conditi
ons returns true
{
//adding characters into empty string
resultStr=resultStr+str.charAt(i);
}
}
System.out.println("String after removing special characters: "+resultS
tr);
}
}

Output

String after removing special characters: ProgrammingLanguage

Replace special Chars to empty


1. String str= "This#string%contains^special*characters&.";
2. str = str.replaceAll("[^a-zA-Z0-9]", " ");
3. System.out.println(str);

Output

This string contains special characters

You might also like