Core Java
Core Java
Core Java
1. Java created By James Gosling - original released by 1995, sub microsystems - oracle
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
-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
Hierarchical:
Hybrid:
Multiple:
Only one class able to extend at compiler time it will not work.
Polymorphism: (static and Dynamic Binding)
Two types of polymorphism in Java: We can perform polymorphism in java by method overloading and
method overriding.
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:
class MultiplyFun {
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 :
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 :
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
}
}
}
System.out.println(strList);
System.out.println(strList1.size());
}
reversedString = reversedString + reverseWord + " ";
}
System.out.print("Reversed string : " + reversedString);
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("");
System.out.println(strList);
Output: [s, k, e, e, G]
Integer Reverse
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");
}
--- array values have 3 index 0,1,2 if we have 3 4,5,6 th index getting error
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:
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 Main() {
// 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
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
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.
//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);
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
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,
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.
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);
while (rs.next()){
String myName = rs.getString(1);
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.
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
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);
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]);
}
}
Severity:
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
-- 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.
-- close, quit
-- send values without using send keys – other option is java script executor.
-- depends on methods
-- file config
ID, name, xpath, css selector, link text, partial link text, class name, tag name, customize xpath.
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'].
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 :
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.
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(invocationCount = 5, threadPoolSize = 2)
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() {
Second EXAMPLE
driver.quit();
}
}
Output – Above test will start a thread pool of 5, and send 100 URL requests to a
specified website.
System.out.println("mobileTesting"+mobileTesting);
System.out.println("emailTextBox"+emailTextBox);
System.out.println("signUpButton"+signUpButton);
Selenium Exceptions:
Data Provider:
Groupsin testng:
Test Cases and Test Scenarios:
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
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
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();
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();
driver.switchTo().window(parent);
parallel="methods"
<test name="ChromeTest">
<classes>
<class name="a_new.Cross_Browser">
</class>
</classes>
</test>
<test name="FirefoxTest">
<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");
}
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");
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Wait Alert is present :
wait.until(ExpectedConditions.alertIsPresent()) !=null);
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.
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)
if(searchBox.isEnabled())
else {
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());
JavascriptExecutor:
Double click:
KeyBoard Event:
Mouse Hover:
Literals
Types of Literals
String Pool:
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.
Static -mutable
mutable
Int a =10;
Int a=20;
Immutable
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.
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.
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
Types:
Single dimensional array
Multidimensional array
Same similarities for array and list
Similarities
o Array and ArrayList both are used for storing elements.
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
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.
Usually, this error is thrown when there is insufficient space to allocate an object in
the Java heap.
Primitive Data Types: A primitive data type specify predefined, The size and type of variable
values are specified ,For example
Non Primitive data Types:
We have 10 values in list, insert new values inbetween easily added as container is said doubly
linked list..
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
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[]){
System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
}
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
public class Main {
Integer myInt = 5;
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;
//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;
@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:
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:
1) Java throw keyword is used to explicitly Java throws keyword is used to declare
throw an exception. an exception.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
String to Int
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,
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);
Output:
Alpha
Beta
Delta
Gamma
Sigma
Java Substring
Java Concatenation:
Split String Numberic character:
String Contains:
BeforeSuite - Report
BeforeTest – Driver launch
BeforeClass
BeforeMethod
Test Case
AfterMethod
AfterClass
AfterTest – pass/fail
AfterSuite – Driver Close/ ReportFlush
this.list.selectByVisibleText(text);
Post Code
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.
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:
while (input != 0) {
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:
//Traversing through the list and printing its text along with link
address
for(WebElement link:allLinks){
System.out.println(link.getText() + " - " +
link.getAttribute("href"));
}
WebElement mytable =
driver.findElement(By.xpath("/html/body/table/tbody"));
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]
Output : [c,b,a,e]
Swap variables
Git Commands:
git clone -b main https://gecgithub01.walmart.com/GlobalRecruitingSystem/SCRPApiAutomation.git
git status
git add .
git branch
Functional testing ensured the functions and features of the application working properly.
Main function
https://www.restapitutorial.com/httpstatuscodes.html
Rewapping project
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"}
)
@CucumberOptions(
features = "src/test/resources/functionalTests",
glue= {"stepDefinitions"},
plugin = { "pretty", "html:target/cucumber-reports" },
monochrome = true
)
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] 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
...
...
5. mvn install
This command builds the maven project and installs the project files (JAR, WAR,
pom.xml, etc) to the local repository.
This command is used to run the test cases of the project using the maven-surefire-
plugin.
HashMap Hashtable
Abstraction
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
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
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.
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.
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:
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.
IAnnotationTransformer
IExecutionListener
IHookable
IInvokedMethodListener
IMethodInterceptor
IReporter
ISuiteListener
ITestListener
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.
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);
W : 2
E : 2
R : 2
W : 1
E : 1
System.out.println(sb);
Output : ru
Select Dropdown without using select class:
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":
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":
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":
if(oSel.isMultiple()){
//Selecting multiple values by index
oSel.selectByIndex(1);
oSel.selectByIndex(2);
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:
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
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.
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.
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> li2 =
driver.findElements(By.xpath("//input[@type='radio']"));
List<WebElement> li3 =
driver.findElements(By.xpath("//input[@type='checkbox']"));
List<WebElement> li5 =
driver.findElements(By.xpath("//input[@type='text']"));
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());
//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 )
System.out.println("one");
}
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/");
driver.findElement(By.xpath("//input[@placeholder='Enter Last
name']")).sendKeys("selenium");
Buttons, links, counts:
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();
RegEx TestNG
https://www.javatpoint.com/how-to-use-regex-in-testng
}
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);
Output
Output