Home Java Overview Maven Tutorials

Wednesday 21 February 2018

Overview of Webservice

What is webservices ?

It's a simple xml based information exchange system, which uses internet for direct interaction between applications.

Watch Video

Components of webservice :
SOAP : Simple object access protocol
UDDI : Universal description and discovery integration.
WSDL :web services descriptive language.
Note : WSDL is a language , used by UDDI.
WSDL(Web Services Description Language)
WSDL is a language for describing web services and how to access them.
ESDL is written in xml.

What is SOAP ?
It is technology which allow communication between different languages. It allow us to pass the data over the internet in easy way.

A simple definition :
SOAP stands for Simple Object Access Protocol.
SOAP can interact with other programming language applications.
It is a just protocol which is XML Based for accessing web services over the internet.
It is recommended by W3C for communication between two application over the network.

Feature of SOAP :
1).It is a communication protocol designed to communicate via internet.
2).It can extend HTTP fro XML messaging.
3).It provide data transport for web services.
4).It can exchange complete documents or call a remote procedure.
5).It can be used for broadcasting a message.
6).It is both platform and language independent.
7).It is the XML way of defining what information is sent and how.
8).It enables the client applications to easily connect to remote services and invoke remote methods.

What is SOAP Message ?
SOAP Messages are just like post-box letter, in letter we have english text and in SOAP message we have XML.
As post-box have envelope, address, message, sender details etc. same in SOAP it have envelope, header, body & fault.

A SOAP message is an ordinary XML document containing the following elements −
Envelope − Defines the start and the end of the message. It is a mandatory element.
Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element.
Body − Contains the XML data comprising the message being sent. It is a mandatory element.
Fault − An optional Fault element that provides information about errors that occur while processing the message.

SOAP Message Structure

What is WSDL ?

WSDL : Stands for Web Service Description Language
1).It is a bese file which is used to describr web service and how to access them.
2).It is written in XML
3).WSDL is the document in XML. Which describe the webservice, the location of that webservice and operations exposed by webservices.
4).WSDL is written in simple XML.

Example of WSDL:-

Click Here or open below link in your browser

WSDL have following major elements :-

type :Describe the data type used by webservices.
message :Messages used by web services.
porttype :Operation performed by web service.
binding :Communication protocols used in web service.

Advantage of SOAP :
SOAP has its own security known as WS Security.
Language and platform independent.
Disadvantage of SOAP :
It support only XML format, it has many standards which we have to follow while working with SOAP UI so that the reason it is slow.
It works with WSDL file onle so we can not use other format like JSON, header , Cookies and so on.

What is REST ?
REST stands for Representational State Transfer

It is platform dependent
It support multiple format like Json, HTML, XML, Plain text file too.
It is fast as compared to SOAP.
It is not a protocol like SOAP it is just a architectural design.

How WebServices works ?

A web service enables communication among various applications by using open standards such as HTML, XML, WSDL, and SOAP.
A web service takes the help of −
XML to tag the data
SOAP to transfer a message
WSDL to describe the availability of service.

OR In another way
Used XML for tagging >> Transfer it to SOAP >> WSDL to get the availabilities of services.

A simple definition: A web service is a function that can be accessed by other programs over the web (Http). To clarify a bit, when you create a website in PHP that outputs HTML its target is the browser and by extension the human being reading the page in the browser. A web service is not targeted at humans but rather at other programs.

Example: I can go to, and type in my home address, and see a map of where I live in my browser.
But what if you were writing a computer program where you wanted to take an address and show a pretty map, just like Google maps?
Well, you could write a whole new mapping program from scratch, OR you could call a web service that Google maps provides, send it the address, and it will return a graphical map of the location, which you can display in your program.

API vs WebService

API and web service both used for communication.
The only difference is that a Web service facilitates interaction between two machines over a network. An API acts as an interface between two different applications so that they can communicate with each other. An API is a method by which the third-party vendors can write programs that interface easily with other programs.


1. All Web services are APIs but all APIs are not Web services. as all tigers are cats but not all cats are tiger

2. Web services might not perform all the operations that an API would perform.

3. A Web service uses only three styles of use: SOAP, REST and XML-RPC for communication whereas API may use any style for communication.

4. A Web service always needs a network for its operation whereas an API doesn’t need a network for its operation.


SOAP is Simple Object Access Protocol
Request and Response > XML Format
Uses Web Services and more secure.

SOAP is a ProtocolREST is an architechtral style
SOAP can not use REST beacuse it is a protocolREST can use SOAP web service because it is a concept and can use any protocol like HTTP, SOAP
SOAP uses services interfaces to expose the business logicREST uses URI to expose business logic
SOAP defines standars to be strictly followedREST does not define too much standard like SOAP
SOAP Requires more bandwidth and resource than RESTREST requires less bandwidth and resource than SOAP
SOAP defines its own securityRESTful web services inherits security measures from the underlying transport
SOAP permits XML data format onlyREST permits different data format such as Plain text, HTML,XML, JSON etc.

Representational State Transfer,
Each URI is representational of some object.
Uses Http get/post/put/delete and uses XML/json/html format
Totally stateless and light weight than soap
Not a protocol rather a architechtural style.

Advantange of REST Services over SOAP Services :

1).Rest Services are light weighted
Means less data transfer between client and server machine, ultimately need less bandwidth and fast.
in non-technical word : SOAP is just like post-office letter/courier where REST is just like post-card.

2).In case of SOAP Service, we can access complete application by using WSDL but in case of REST we can access only 1 functionality(Resource) by using URI, no need to access complete application.
Advantange for service provider is that they can sell complete application as well as only part of application, it will bring more small customer to it.

3).Soap Support only XML format for data exchange. Rest support HTML, XML, JSON , plain text, PDF etc.

4).SOAP service mainly support GET but Restful services uses for main HTTP methods :
a).GET to retrieve resource
b).POST to create resource
c).PUT to update resource
d).Delete to delete resource

5).SOAP defines standards(W3C) to be strictly followed(Which will take more time to develop, test and use) but REST does not define too much standards like SOAP.

What is URI ?

URI : Uniform Resource Identifier
Identifyng documents using a short of numbers, letters and symbol.

URL and URN A URN(Uniform Resource Name) ia an internet resource with a name.

Example of URI :


WSDL : The web service description language(WSDL) is an XML vocabulary used to describe SOAP-based web services.
WSDL files that we will be using for SOAP based web services only.
It's major elements are :
Definition : root element of all WSDL documents, It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.
Datatype : The data types to be used in the messages are in the form of XML schemas.
Message : It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.
Binding : It is the concrete protocol and data formats for the operations and messages defined for a particular port type.
Operation : It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message.
Port : It is a combination of a binding and a network address, providing the target address of the service communication.
Service : It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.

WADL : The web application descrition language(WADL) is an XML vocabulary used to describe RESTful web services and XML vocabulary for expressing the behaviour of HTTP resources.
main porpose to define the contact.

What is SOAP UI?

Soap UI is an open-source tool used for functional and non-functional testing,widely used in web-services testing.

SOAP UI important feature

1).It is capable of performing the role of both client and service.
2).It enables the users to create functional and non-functional tests quickly and in an efficient manner using a single environment.
3).It is licensed under the terms of the GNU Leaser General Public Licence.
4).It is purely implemented wing JAVA platform.
5).It supports Windows, Mac, multiple Linux dialects.
6).It allows testers to execute automate functional, regression, compliance and load tests on different WEb API.
7).It supports all the standard protocol and technologies to test all kind of APIs.

1).Soap UI is a tool from Samrtbear mainly for functional testing but it can also be used for non functional testing like performance, security of web services.

2).Web services can be created either by SOAP or REST method, we can work with both.

3).There are two version of SOAP UI in market :
SOAP-UI free
SOAP-UI Pro paid.


1). Webservice is the type of application or software component which does not provide any GUI for user to interact.

2). We can interact that kind of application passing input to specified XML format and receiving result in XML.

3). Webservive use HTTP protocol to communicate wth web service.

4).Web services are powered by XML and thee other core technologies: WSDl, SOAP and UDDI.

Type of WebService

SOAP Services (WSDL File)
REST Services (WADL File, URI)

Demo Soap Services


1).In Soap UI first we need to create a workspace.
2).Workspace is a place where all our projects will be saved.
3).Workspace is a single XML file, we have multiple projects in a sigle workspace.
4).It is Simillar like Domain, we can have multiple projects in a single domain.

How to download and install the SOAP UI

navigate to below url :
or click here

Click here to download from drive

Tuesday 20 February 2018

HTTP Request and HTTP Response

<script async src="//"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-6658533981545355", enable_page_level_ads: true }); </script>

Hello Friends,

Before starting the API Testing a tester must know what is HTTP Request and HTTP response, so this article mainly cover :
HTTP Request
HTTP Response

The HTTP Protocol :

HTTP : Hypertext Transfer Protocol

The HTTP is an application layer protocol(OSI Model) that allows web-based applications to communicate and exchange data.

OSI Layers are as below:
Presentation Session
Data Link

OSI model in detailed view :

What is HTTP?

The HTTP is the messenger of the web
It is a TCP/IP based protocol
It is used to deliver content for example images, videos, audios, documents etc.
The computer that communicate via the HTTP must speak the http protocol

Three Important things about HTTP

1). HTTP is connectionless means after making the request, the client disconnect from the server, then when the response is ready the server re-establish the connection again and deliver the response.
2). The HTTP can deliver any sort of data, as long as the two computers are able to read it.
3). The HTTP is a stateless means the client and server know about each other just during the current request, it is closes and the two computers want to connect again, they need to provide information to each other anew, and the connection is handled as the very first one.

Key points :

1).The HTTP is a TCP/IP based application layer protocol that allows web based applications to communicate and exchange data.
2).The computers that communicate via the HTTP must speak the http protocol.
3). The http is stateless, connectionless and can deliver any data.
4).We use the http protocol bacause it is a convenient way to quickly and reliably move data on the web.
5). The request response cycle works on the web via http messages.
6). A http message contains three sections the start line, the header and the body.
7).The http request message differs from the http response messages.

Cycle of HTTP Request & Response

HTTP Request :

An HTTP client sends an HTTP request to a server and basically this request is a packet of information.
This packet ave binary data sent by the client to the server.

HTTP Request contains following three things :

1). Request Line
2). zero or more header (General|Request|Entity) fields followed by CRLF
and an empty line(i.e. a line with nothing preceding the CRLF)
indicating the end of header fieds
3). Message body of request (Optionally)

Two HTTP Request Methods:


Two commonly used methods for a request-response between a client and server are: GET and POST.
GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource

Request line have Request Method, Request URI, HTTP Protocol

Request Header : In the request section, whatever follows Request Line till before Request Body everything is a Header.
Headers are used to pass additional information about the request to the server.

Request Body is the part of the HTTP Request where additional content can be sent to the server.
For example, a file type of JSON or XML.

Let's better understand by below Image :

HTTP Response :

After successfully receiving and interpreting a request message, server responds with a HTTP response message.
This response is the packet of information sent by server to the client.
As like HTTP Request, HTTP Response also have three things :

1).A status Line
2).Zero or more header (Genreal|Response|Entity) fields followed by CRLF
An empty line (i.e. a line with nothing preceding the CRLF)
indicating the end of the header fields
3). Message Body (optionally)

Status line has , HTTP Protocol version, Status code like 200, and Status message as OK,
Response header, Response Header also contains zero or more Header lines. However, it is very uncommon to have zero Headers in the response. Lines just after the Status Line and before the Response Body are all Response Headers lines.
Response Body , Response Body contains the resource data that was requested by the client.
Note: Response Body contains text in JSON format, as one of the Response headers suggested.
can better understood by below image :

HTTP Staus code :

1xx Informational response :
100 Continue
101 Switching Protocol
102 Processing
103 Early Hints

2xx Success :
200 OK
201 Created
202 Accepted
203 Non-Autoritative Information
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status
208 Already Reorted
226 IM Used

3xx Redirection :
300 Multiple choices
301 Moved Permanently
302 Found
303 see other
304 Not Modified
305 Use Proxy
306 Switch Proxy
307 Temporary Redirect
308 Permanent Redirect

4xx Client errors :
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Payload Too Large
414 URI Too Long
415 Unsupported Media Type
416 Range Not Satisfiable
417 Expectation Failed
418 I'm a teapot
421 Misdirected Request
422 Unprocessable Entity
423 Locked
424 Failed Dependency
426 Upgrade Required
428 Precondition Required
429 Too Many Requests
431 Request Header Fields Too Large
451 Unavailable For Legal Reasons

5xx Server errors :
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
506 Variant Also Negotiates
507 Insufficient Storage
508 Loop Detected
510 Not Extended
511 Network Authentication Required

Click here for next topic

click here for previous topic

API Testing Overview


Hello Friends,

In this article , i will describe that what is API? what is API Testing? and an overview of API.

What is API? (Application Programming Interface)

API is a software intermediary that use to allow two applications to talk to each other,
basically an API specifies how software components should interact.
It consists of a set of routines, protocols and tools for building the Software Application.
OR in simple words
API essentialy a library of functions, data structure and classes used by the developer to perform a specific task such a drawing a window and posting a comment etc.

Example of API :

Each time when you use an app like Twiiter, Facebook, send an instant message, or check the weather on your phone, you are using an API.

When we use an applicaton on our mobile phone, the application connects to the internet and sends data to a server, then the server retrives that data, interprets it, perform the necessary actions and sends it back to our phone.
The application then interprets that data and presents you with the information you wanted in a readable way.
This is that an API is - all of this happens via API.

Popular API Examples :

Google Maps API : Google Maps APIs lets developes embed Google Maps on weboage using a JavaScript or Flash Interface.

YouTube API : Google's APIs lets developers integrate YouTube videos and functionality into websites or applications.

Twitter APIs: Twitter offers two APIs. The REST API allows developers to access core Twitter data and the Search API provides methods for developers to interact with Twitter Search and trends data.

Amazon Product Advertising API: Amazon's Product Advertising API gives developers access to Amazon's product selection and discovery functionality to advertise Amazon products to monetize a website.

What is API Testing ?

As like other kinds of testing, API testing also is intended to reveal bugs : inconsistencies or deviations from the expected behaviour.
Continuous testing is also very important to make sure it continues to work when the public has access to it.
API testing is one of the most challenging parts of the chain of software and QA testing because it works to assure that our digital lives run in an increasingly seamless and efficient manner.
API testing as a part of integration testing to determine if they meet expectations for functionalit, reliability, performance and security.

let's discuss on Three layer Software Architecture :

Presentation layer: This layer contains the user oriented functionality responsible for managing user interaction with the system, and generally consists of components that provide a common bridge into the core business logic encapsulated in the business layer.

Business layer: This layer implements the core functionality of the system, and encapsulates the relevant business logic. It generally consists of components, some of which may expose service interfaces that other callers can use.

Data layer: This layer provides access to data hosted within the boundaries of the system, and data exposed by other networked systems; perhaps accessed through services.

Api testing is mainly exist on the business logic layer of the software architecture.
Remember : Api testing won't focus on the look and feel of an application.

Important Point : API Testing is not either black box or white box basically its both black and white.

API testing is now considered critical for automation testing because APIs now serve as the primary interface to application logic and because GUI tests are difficult to maintain with the shortrelease cycles and frequent changes commonly used with agile Software Development and Devops.

Types of API testing
API testing typically involves the following practice :
Unit Testing
Functional Testing : Incluse test case definition, execution, validation and regression testing.
Load testing
Runtime error detection : Monitoring an application the execution of automated or manual tests to expose problems such as race conditions, exceptions and resource leaks.
Security testing : Include penetration testing and fuzz testing as well as validation authentication, encryption and access control.
Web UI testing
Interoreability testing -(SOAP only) checking conformance to web services Interoperability profiles.
Compliance testing (SOAP only)

API Architecture

API Call Collector
1). HTTP Header
2). HTTP Request
3). Status code/response code

HTTP header
a) Automatization
b) Response Time

HTTP request
c. GET
g. PUT

Response code like 404 (Not Found), 200(OK) etc.

Types of Web Service

1). SOAP (Simple Object Access Protocol)
2). REST (Representational state transfer)

Popular API Testing Tools :
SWAGGER (Manual API Testing)
API Studio
Amazon webServices

Advantage of API Testing

Test of core functionality
Test Quality
Faster Release
Test coverage with application
Access to application without user interface
Protection from malicious code and breakage
Time Efficiency Vs. Functional and Validation testing
Cost Effective/Reduce Testing cost
Technology independent.. etc

Types of bugs expected :
Wrong status code
API validation
Components (module) not interacting as expected
HTTPS request are not working.

Difference between Unit Testing and API Testing
UNIT Testing API Testing
Owned by development Owned by test
Limited in Scope Broader in scope
Mocked dependencies Mocked and real dependencies
Does it work by itself Does it play well with others
Usually ran before check-in Ran after the build created

API Test Design Principles

Robust automated test cases generally have 5 stages of API test design
1).Setup : Initialize data, create objects, start services etc.
2).Execution : Steps to exercise API or scenario, also logging
3).Verification : Oracles to evaluate execution outcome
Note : Oracles are messages function usally used to compare actual result with expected results
4).Reporting : pass, fail or blocked
5).Clean up : Pre-test state.

Key Points:

API testing benefits both the development and testing organization.
API testing is both a black and white box activity
Find some types of bugs more efficiently but not find all bugs
Doesn't evaluate "look and feel"
Can change focus of GUI automation
Not for everyone.

Approach of API Testing
1).First understand the funcationality of your API program and find the scope of this program.
2). Then simply apply your testing techniques like error guessing, input parameters , boundary value etc.
3). Now time have come to execute your test case & compare the result with expected results.

Click Here for Next Topic

Tuesday 13 February 2018

How To Handle Tabs in selenium

Hello Friends,

In this article , i will describe that how to handle the Tabs in selenium.
So we will cover below scearios :

For Video part 1:

Click here

For Video part 2:

Click here

Scenario :1-
Open the browser & enter Url Open a new tab
Hit a url in new tab
perform some operation in new tab
come back to main tab

Scenario :2-
Open the browser & enter Url
click some link which will open the new tab
switch to newly opened tab
perform some operation
come back to main tab
Scenario :3-
Open the browser & enter Url click on link which will open the new tab
switch to newly opened tab
close newly opened tab only
perform some operation in your main tab

So, here we will write some simple code to do these operations :-

Method 1

Selenium 3

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
public class practice
WebDriver driver;
public void tabs() throws InterruptedException, AWTException
{ System.setProperty("", "./Driver\\chromedriver_99.exe");
System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");
System.setProperty("", "true");
driver = new ChromeDriver();

String parentwindow = driver.getWindowHandle();
//Open the New Tab
Robot robot = new Robot();
ArrayList tabs = new ArrayList(driver.getWindowHandles());
driver.switchTo().window((String) tabs.get(1));

Method 2

Selenium 4

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.testng.annotations.Test;
public class practice
WebDriver driver;
public void tabs() throws InterruptedException, AWTException
System.setProperty("", "./Driver\\chromedriver_99.exe");
System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");
System.setProperty("", "true");
driver = new ChromeDriver();
String parentwindow = driver.getWindowHandle();
//Open the New Tab
//Switch Back to previous window

Before Selenium 4, we were using getWindowHandle & getWindowHandles methods.

driver.getWindowHandle() will return the String so below is syntax :

String currentwindow = driver.getWindowHandle();

Set windows = driver.getWindowHandles(); OR
List list = driver.getWindowHandles();

but in Selenium 4 We can handle the tabs as below :-
WebDriver newTab = driver.switchTo().newWindow(WindowType.TAB)
WebDriver newwndow = driver.switchTo().newWindow(WindowType.WINDOW);

Tuesday 6 February 2018

Send Reports Automatically to Email using Maven from Eclipse

Hell Friends,

In this article we will discuss

How to Send Reports Automatically to Email using Maven from Eclipse by Post-Man plugin

For Video :

Click here

This is very simple, you just need to add some plugin & remaining things will be same.
So steps will be as below :
Step 1 : Create a Maven Project.
Step 2 : Add Dependency as below in your POM.xml file.
Step 3 : Update the project.
Step 4 : Convert your Execution file to TestNG xml file & place it in main source folder(if using below plugins).
Step 5 : Set email address & report path.
Step 6 : Now Run your POM.xml file.

To Download the complete plugin in notepad click the below link :

click here

Alternatively, one can copy the below plugin & paste in his Maven Pom.xml file.

<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">
<!-- -->
<!-- -->
<id>send a mail</id>
<!-- From Email address -->
<!-- Email subject -->
<subject>Test Automation Report</subject>
<!-- Fail the build if the mail doesnt reach -->
<!-- host -->
<!-- port of the host -->
<!-- Email Authentication(USername and Password) -->
<mailuser>Enter email id here</mailuser>
<mailpassword>Enter password here</mailpassword>
<!-- To Email address -->
<!-- Report directory Path -->
<!-- Report file name -->
<!-- Use Regular Expressions like **/*.html if you want all the html files to send-->

Here is the sample code

package com.lang.Execution;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ReportTest
WebDriver driver;
ExtentReports report;
ExtentTest logger;
public void navigate() throws InterruptedException, IOException
System.setProperty("", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver=new ChromeDriver();
report=new ExtentReports("./Reports/TestReport.html");
@Test(priority = 0)
public void title()
logger.log(LogStatus.INFO, "test started ");
System.out.println("Your Title is :" + driver.getTitle());
String title = driver.getTitle();
if(title.equalsIgnoreCase(" Online Software Testing: Software Testing"))
logger.log(LogStatus.PASS, "Test Verified");
logger.log(LogStatus.FAIL, "Test Failed");
//Flush the data to report
@Test(priority = 1)
public void clicklink(){
//Create object for Report with filepath
//report=new ExtentReports("./Reports/TestReport.html");
//Start the test
//Log the status in report
logger.log(LogStatus.INFO, "Test started ");
//Pass the test in report
logger.log(LogStatus.PASS, "Link Verified");
//End the test
//Flush the data to report

Tags :

how to send report through email in selenium webdriver,Sending Selenium Reports through mail,
Advance Selenium Reporting- Selenium Webdriver tutorial How to Send a Report via Email in selenium,
How to generate and send HTML reports using Selenium WebDriverSend Reports Automatically to Email using Maven from Eclipse
Robotically Send Test Reports via Mail Using Maven Postman PluginHow to send Test result to email using maven by postman plugin
how do i send a email test report from maven,How to send an automated email with test reports using Maven and TestNG,

Core Java Interview Questions for Selenium tester

Hell Friends,

In this article we will discuss about Java interview Questions for Selenium Tester :

0. Write a program to find occurance of letter in a given string

Answer :- First change the string in Character Array then for each character run a for loop to find another character in String.

Below is program

public class PracticeA {

public static void main(String args[]) {
String x = "aabbbccccdddee";

char[] ch = x.toCharArray();

Map<Character , Object> mp = new HashMap<Character, Object>();

for(int i = 0; i<ch.length; i++) {
int counter = 1;
if(mp.containsKey(ch[i])) {
System.out.println("letter already present");

else {
System.out.println("letter not present");
for(int j =0; j<ch.length; j++) {
if(ch[i]==ch[j]) {
mp.put(ch[i], counter);

Output :- {a=2, b=3, c=4, d=3, e=2}

1. Write a program to reverse the sentense

Answer :- First split the string by spaces (" "), then store in an Array and finally print the array in reverse order.

Below is program

public class Sentensereverse
static String str = "my name is chandan";
static String str3 = "";
public static void main(String[] args)
String s[] = str.split(" ");
for(int j=s.length-1;j>=0; j--)
str3 = str3 + " "+s[j];

Output :- chandan is name my

2. Write a program to reverse the Word in java

Answer :- We will create a blank string variable and will break the input word in character by method charAt().

Below is program

public class Sentensereverse
public static void main(String[] args)
String str = "chandan";
String str2 = "";
for(int i = str.length()-1; i>=0; i--)
str2 = str2 + str.charAt(i);

Output :- nadnahc

3. Write a program to sort the array in java

Answer :- We will compare each element to rest of all elements if element is greater , then we will swap them.

Below is program

public class Sortarray
int[] arr = {4, 20, 9, 15, 7, 11};
public static void main(String args[])
Sortarray obj = new Sortarray();
public void sarray()
for(int i =0; i<arr.length; i++)
for(int j =0; j<arr.length; j++)
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
for(int element : arr)

Output :- 4 7 9 11 15 20

4. Write a program in java to find number is prime or not

Answer :- If any number is divisible by only 1 or self then that number is known as prime number. .
So we will divide that number from 2 to just 1 digit before to testing number.
if remainder is zero then number is prime otherwise number is not prime.

Below is program

public class Test2
public static void main(String[] args)
Scanner scn = new Scanner(;
System.out.println("Enter the number");
boolean flag = false;
int x = scn.nextInt();
if(x == 0 || x == 1)
System.out.println("Invalid number Entered");
for(int i = 2; i<=x/2; i++)
if(x%i == 0)
flag = true;
System.out.println("Number is not prime");
System.out.println("number is prime");

Output :- NUMBER is prime


5. Write a program to check the Word is palindrome or not in java

Answer :- Simply reverse the string and then compare new reversed string to test string, if both are same Strings are palindrome .

Below is program

public class Test2
public static void main(String args[])
Scanner scn = new Scanner(;
System.out.println("Enter the string");
String test =;
String ptest = "";
for(int i = test.length()-1; i>=0; i--)
ptest = ptest + test.charAt(i);

System.out.println("String is palindrome");
System.out.println("String is not palindrome");

Output :- Enter the string
String is palindrome

Write a program in java to remove first and last letter alternatively and print

Answer :- The above problem is easy, just a combination of three logics
First:, remove first letter from String
Second:, remove last letter from String
Third:, call above above methods alternatively
and combine all three logic with any loop to get the answer

Below is program

public class CscPractice {
public static void main(String args[]) {
String x = "chandan";
do {
x = firstcut(x);
if(x.length()>1) {
x = lastcut(x);
public static String firstcut(String s) {
s = s.substring(1, s.length());
return s ;
public static String lastcut(String s) {
s = s.substring(0, s.length()-1);
return s;

Output :-

. Distinguise numbers & letter from a string, given "way2testing"

Answer :- First we will get the character of string and for each character we will check whether it is number or letter by method Character.isDigit(), then we will put the appropraite character in different String or array.

Below is program

public class ChandanSP
public static void main(String args[])
String num = "";
String purestr = "";
String x = "way2testing";
for(int i = 0; i<x.length(); i++)
char ch = x.charAt(i);
num = num + ch;
purestr = purestr +ch;

Output :-


. Find number of letter, number of digits and number of special character in a String

Answer :- First we need to convert the String into character array(.toCharArray())
now with the help of below two character class method, we can find letter and numbers and remaining will be the special character
Character.isDigit(), Character.isLetter() .

Below is program

public class JavaPractice {
public static void main(String args[]) {
String S = "123abcde@#$%&";
int number = 0;
int letter = 0;
int special = 0;
char c[] = S.toCharArray();
for(char a : c) {
if(Character.isDigit(a)) {
else if(Character.isLetter(a)) {
else {
System.out.println("Numbers are " +number);
System.out.println("letters are " +letter);
System.out.println("Special are " +special);

Output :-
Numbers are 3
letters are 5
Special are 5


. Reverse a String , without using any inbuild methods

Answer :- Convert the string into byteArray, then reverse the array
and by using below method change array to String String s = new String(byte)


Below is program

public class JavaTutorial {
public static void main(String args[]) {
String x = "Chandan";
byte[] bytes = x.getBytes();
byte num[] = new byte[x.length()];
for(int i = 0; i<bytes.length; i++) {
num[i] = bytes[bytes.length-(i+1)];
for(byte xx : num) {
String m = new String(num);

Output :-


0.What is Java?
Java is a programming language and computing platform first released by Sun MicroSystems in 1995.

1. What is a JVM?
JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

2. Does Java support multiple inheritance?
Java doesn't support multiple inheritance.

3. What is the most important feature of Java?
Java is a platform independent language.

4. What is difference between Path and Classpath?
Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

5. What are instance variables?
Instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.

6. What is a pointer and does Java support pointers?
Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.

7. What is the return type of the main() method?
Main() method doesn't return anything hence declared void.

8. What are local variables?
Local variables are those which are declared within a block of code like methods. Local variables should be initialized before accessing them.

9. Is Java a pure object oriented language?
Java uses primitive data types and hence is not a pure object oriented language.

10. Is JVM platform independent?
JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor.

11. Can a main() method be overloaded?
Yes. You can have any number of main() methods with different method signature and implementation in the class.

12. What is the base class of all classes?

13. What do you mean by platform independence?
Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

14. Are arrays primitive data types?
In Java, Arrays are objects.

15. What is the difference between a JDK and a JVM?
JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

16. Does the order of public and static declaration matter in main() method?
No. It doesn't matter but void should always come before main().

17. What is the impact of declaring a method as final?
A method declared as final can't be overridden. A sub-class can't have the same method signature with a different implementation.

18. Can a class be declared as protected?
A class can't be declared as protected. only methods can be declared as protected.

19. How to define a constant variable in Java?
The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed also. static final int PI = 2.14; is an example for constant.

20. Which package is imported by default?
java.lang package is imported by default even without a package declaration.

21. What is the argument of main() method?
main() method accepts an array of String object as argument.

22. Can a source file contain more than one class declaration?
Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public.

23. What is the access scope of a protected method?
A protected method can be accessed by the classes within the same package or by the sub classes of the class in any package.

24. Can a class declared as private be accessed outside it's package?
Not possible.

25. Why is the main() method declared static?
main() method is called by the JVM even before the instantiation of the class hence it is declared as static.

26. What is the purpose of declaring a variable as final?
A final variable's value can't be changed. final variables should be initialized before using them.

27. What is a package?
Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

28. Can a main() method be declared final?
Yes. Any inheriting class will not be able to have it's own default main() method.

29. I don't want my class to be inherited by any other class. What should i do?
You should declared your class as final. But you can't define your class as final, if it is an abstract class. A class declared as final can't be extended by any other class.

30. Should a main() method be compulsorily declared in all java classes?
No not required. main() method should be defined only if the source class is a java application.

31. When will you define a method as static?
When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.

32. What is the importance of static variable?
static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

33. How is final different from finally and finalize()?
final is a modifier which can be applied to a class or a method or a variable. final class can't be inherited,final method can't be overridden and final variable can't be changed.
finally is an exception handling code section which gets executed whether an exception is raised or not by the try block code segment. finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

34. I want to print "Hello" even before main() is executed. How will you achieve that?
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.

35. Can we declare a static variable inside a method?
Static variables are class level variables and they can't be declared inside a method. If declared, the class will not compile.

36. Can a abstract class be defined without any abstract methods?
Yes it's possible. This is basically to avoid instance creation of the class.

37. Can you give few examples of final classes defined in Java API?
java.lang.String, java.lang.Math are final classes.

38. Can a abstract class be declared final?
Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

39. Can you create an object of an abstract class?
Not possible. Abstract classes can't be instantiated.

40. What are the restriction imposed on a static method or a static block of code?
A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.

41. Can a Class extend more than one Class?
Not possible. A Class can extend only one class but can implement any number of Interfaces.

42. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided implementation for method m2. Can i create an object of Class C?
No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.

43. Can a class be defined inside an Interface?
Yes it's possible.

44. Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

45. What is use of a abstract variable?
Variables can't be declared as abstract. only classes and methods can be declared as abstract.

46. Can an Interface be defined inside a class?
Yes it's possible.

47. What is an Abstract Class and what is it's purpose?
A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

48. Can an Interface be final?
Not possible. Doing so so will result in compilation error.

49. Can an Interface implement another Interface?
Interfaces doesn't provide implementation hence a interface cannot implement another interface.

50. Why does Java not support operator overloading?
Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn't support operator overloading.

51. Is there any difference between an argument and a parameter?
While defining methods, you pass variables which you refer as parameters. And when you call these methods and pass values for the variables then they are phrased as arguments.

52. How your program would behave if you declare the main method as private?
It would get compiled correctly but will throw the error "Main method not public." at runtime.

53. Q: What difference you see between pass by reference and pass by value in Java?
Pass by reference indicates, passing the address itself rather than passing the value. Pass by value means is giving a copy of the value.
Example : Actions action = new Actions(driver);

54. Can you compile a Java class successfully without having the main method?
Yes, we can compile, but it won't run. The
method works as the startup function for a Java class, and the JVM calls it for the program execution.

55.What do you make of System, out and in the function System.out.println()?
System -> A predefined final class,
out -> PrintStream object and,
The -> built-in overloaded method of the out object.

56.Q: How would you prove that an array is not null but is empty?
Call the . It will print 0. That suggests that the array is empty. If it would've been null then, it would've thrown a on calling the .

57. Q: What do you understand of Garbage Collection and how to call it explicitly?
If the object is no longer belong to any variable, Java automatically reclaims the memory. This process is known as garbage collection. You can use the method to call it explicitly.
For more :

Click here

Frequently Asked Selenium Interview Questions and aswers

Hell Friends,

In this article we will discuss about basic Selenium interview Questions for Selenium Tester :

0.What is Automation Testing?
When Testing script/cases/tests run by some robot/tool , then it will become automation testing.

1. What is selenium?
A tool, which will automate your web browser.

Question :- What is the difference between CSS & Xpath?
Answer :- Difference Between CSS & Xpath
There are some differences between xpath and css listed below −

1).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.

2).Xpath is slower in terms of performance and speed. Css has better performance and speed than xpath.

3).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.

4).Xpath expression is represented by [//tagname[@attribute = 'value']. The css expression is repression is represented by [tagname[attribute = 'value'].

5).There are two types of xpath – absolute and relative. But css has no such types.

Question :- Why do we write WebDriver driver = new ChromeDriver(), explain?

Answer :- WebDriver driver = new ChromeDriver();
WebDriver is an interface and all the methods which are declared in WebDriver interface are implemented by respective driver class.
We generally do it this way because usually we want to be able to run our tests on multiple browsers. If we declare the driver as a specific driver type, we are then anchored to only that driver. This is not a problem if you only ever need to test on say Chrome for example. But what if you later want your tests to also be able to work with IE, Opera, Firefox, etc.? These are extended classes of the WebDriver interface.
If your main tests and other classes define the commonly shared driver as simply WebDriver instead of specifically being tied to ChromeDriver, then the same tests can be run without change to the test code itself simply by initializing the shared driver object with a different driver extended class.
Let’s see why can’t we use the following statement.
WebDriver driver = new WebDriver();
We cannot write our code like this because we cannot create Object of an Interface.
WebDriver is an interface.

Question :- Difference between Implicit wait & explicit wait?
Answer :- 1). Implicit-wait :- The driver is asked to wait for a specific amount of time for the element to be available on the DOM of the page. It is a global wait and applied to all elements on the webpage.
It affects the execution speed since each step waits for this wait till it gets the element it is looking for.
The implicit wait timeout is set to 0 by default.

Explicit-wait:- The driver is asked to wait till a certain condition is satisfied.It is not a global wait and applied to a particular scenario.
It does not affect the execution speed since it is applicable to a particular element of the page.
WebDriverWait objwait = new WebDriverWait(obj, 10); // this will wait for 10 seconds
Note : - The default polling time is 500 mili seconds.
So until your wait condition is true and the specified time is not over , the WebDriver checks for the element once every 500 mili seconds.

Question :- Staleness exception of selenium ?
Answer :-A stale element reference exception is thrown in one of two cases, the first being more common than the second:
The element has been deleted entirely.
The element is no longer attached to the DOM.
Solution : Refreshing the web page

Question :- How to Handle Disabled Elements in selenium ?
Answer :- WebElement dis = driver.findElement(By.xpath("//*[@id='csc']/button"));
System.out.println("Not enabled");

Question :- How to Handle hidden elements in selenium?
Answer :- WebElement element = driver.findElement(By.xpath("/html/body/p"));
JavascriptExecutor js = (JavascriptExecutor)driver;
String y2 = (String) js.executeScript("return arguments[0].innerText", element);

Question :- Staleness exception of selenium ?
Answer :-A stale element reference exception is thrown in one of two cases, the first being more common than the second:
The element has been deleted entirely.
The element is no longer attached to the DOM.
Solution : Refreshing the web page

Question :- What is Call by value & call by refrence in Java??

Answer :-
Call by Value :A copy of actual arguments is passed to respective formal arguments.
"Both types of parameters are stored in different locations."
"Any changes inside functions are not reflected in actual parametrs of caller".

Call by Reference :- Both actual and formal parameters refer to same locations and any changes made are reflected in actual parameters of caller.
Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.
Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.

Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.

The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters.

Example of call by value:-
public class Practice
static int x = 10;
static int y = 20;
public static void main(String args[])
Practice obj = new Practice();
System.out.println(obj.sum(x, y));
System.out.println(obj.sum(obj.x, obj.y));
public int sum(int a, int b)
int c = a+b;
return c;

Output :-

Example of call by Reference:-

class simpleone
String name;

public class Practice
public static void main(String args[])
Practice obj = new Practice();
simpleone obj1 = new simpleone();
public static void transform(simpleone obj2)
{ = "way2testing";

Output :-

Question :- Assert & verify in selenium?
Answer :- Both Assert and Verify commands are used to find whether a given input is present or not on the webpage. There are some difference between Assert and Verify in Selenium.

Assert command in selenium:
When an “assert” command fails, the test execution will be aborted. So when the Assertion fails, all the test steps after that line of code are skipped.
The solution to overcoming this issue is to use a try-catch block. We use the Assertion in the try catch block. Mostly, the assert command is used when the end result of the check value should pass to continue to the next step.

Verify command in selenium:
When a “verify” command fails, the test will continue executing and logging the failure.
Mostly, the Verify command is used to check non-critical things.
In such cases where we move forward even though the end result of the check value is failed.

Example of Soft & Hard Assert :-
public class Practice
public void Tes()
int x = 10;
int y = 20;
SoftAssert sa = new SoftAssert();
sa.assertEquals(x, y);
System.out.println("I will be executed only after soft assertion");
Assert.assertEquals(x, y);
System.out.println("I will not be executed");

Example of verify :-
executed when condition is true
executed when condition is false

executed when condition is true
catch(Exception e)
executed when condition is false

Friday 2 February 2018

How to Handle Frames in Selenium

Hell Friends,

In this article i will describe how to handle the frame , we will get the answers of below questions :

For Video :-

Click Here

1). How to switch to Frame
2). How to handle alert/confirmation on frame.
3). How to switch between the frames.
4). How to come back from frame to main window.

I have created a Web page , which have two frames & in first frame there is some alerts/confirmation etc as shown below :-




Scenarios are as :

Navigate to WebPage
Enter the data in text box
Switch to frame 1
Click on alert
Accept the alert
Switch to frame 3
click on webelment
Switch to frame 2.
click on element

Here is sample code
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Framedemo
WebDriver driver;
public void g() throws InterruptedException, IOException
System.setProperty("", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver=new ChromeDriver();
@Test(priority = 0)
public void switchframe() throws InterruptedException
driver.findElement(By.xpath("html/body/input")).sendKeys("welcome to way2testing");
List framecount = driver.findElements(By.tagName("iframe"));
System.out.println("Total frames on page are : " + framecount.size());

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.switchTo().frame(driver.findElement(By.xpath(".//*[@title = 'ifsccode']")));
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

Frame Pages for Practice