Java Programs for selenium Interview

Java Programs for selenium Interview:-
During the job hunting following are the java programming questions surely asked you in selenium interview. I know most of the programs you have prepared  in graduation itself. Here we are providing some programs to crack your selenium interview.
1] Program to print Factorial number in java
package basic;
public class Factorial {
public static void main(String[] args) {
// by decrement *
int k = 5;
int fact = 1;
for (int i= 5 ; i>= 1; i–){
fact = fact * i;
// by increment
int a = 8;
int ft = 1;
for (int b= 1 ; b<= 8; b++){
ft = ft * b;

2] Program to print Reverse string using and without using reverse function
package basic;
public class StringRev {
public static void main(String[] args) {
/*StringBuffer buffer = new StringBuffer(“Kumar”);
String str =”Shweta”;
for(int i=str.length()-1; i>=0; i–)

3] Program for Fibonacci series number in java
package basic;
public class Febonaci {
public static void main(String[] args) {
int x = 0;
int y = 1;
int count = 10;
int z;
for (int i = 2; i <count; i++){
z= x + y;
x = y;
y = z;

4] Print Prime number in java
package basic;
public class PrimeNumb {
public static void main(String[] args)
int num=9;
int i;
for( i=2; i<num; i++)
System.out.println(“number is prime”);
System.out.println(“number is not prime”);

5] Programe for Palindrome in java
package basic;
public class Palindrome {
public static void main(String[] args) {
String str = “Kumar”;
int i=0;
int j= str.length()-1;
System.out.println(“String is not palindrome”);
System.out.println(“String is palindrome”);

Posted by Kumar in Selenium, 0 comments

How to read Excel File in Selenium

How to read Excel File in Selenium Webdriver
Step – 1 Create excel file and save in any location or import / drag in selenium package where jars are stored.
Step – 2 Make sub program
– Make class
– Create method including file path, file name and sheet name
– Make file instance
– Take FileInputStream obtains input bytes from a file in a file system
– Create workbook
– Check excel file extension
– Check sheet data row by row

package excelProgram;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcl {
public void readXL(String filePath, String fileName, String sheetName) throws IOException
//eclipse support one forward slash (/) or two backword slash (\\)
File file = new File(“E:\\Documents and Settings\\Kumar\\Desktop\\DataExl.xlsx”);
// OR we can also use bellow line instead of above
//File file = new File(filePath+”//”+fileName);
FileInputStream inputStream=new FileInputStream(file);
Workbook workbook=null;
String extension = fileName.substring(fileName.indexOf(“.”));
if (extension.equals(“.xlsx”))
//If excel file extension is .xlsx then we use XSS method
workbook= new XSSFWorkbook(inputStream); //Initializing workbook object
//If excel file extension is .xls then we use HSS method
workbook=new HSSFWorkbook(inputStream);
Sheet sheet=workbook.getSheet(sheetName);
int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();
for (int i=0;i<rowCount+1;i++)
Row row=sheet.getRow(i);
for (int j=0;j<row.getLastCellNum();j++)
System.out.println(row.getCell(j).getStringCellValue()+” “);

Step – 3 Make Main program
– Write file path
– Make sub program object
– Read object
package excelProgram;
public class MainRead {
public static void main(String[] args) throws IOException {
// File path location user.dir
String filePath=System.getProperty(“E:\\Documents and Settings\\Kumar\\Desktop\\DataExl.xlsx”);
// OR we can also use bellow line instead of above
//String filePath=System.getProperty(“user.dir”)
ReadExcl obj= new ReadExcl();
// ReadExcl from other file

Posted by Kumar in Selenium, 0 comments

Basic Java Interview Questions For Selenium

Following are the list of basic Java interview questions can be asked in selenium interview. Interviewer can ask to check your understanding of java as a programming language.
Question: – What is JRE and why it is required?
Answer: – Java Runtime Environment (JRE) is a runtime component of java software can be used to run any java application which can comprises JVM, classes and supporting libraries.          Question: – What is JVM?
Answer: – Java Virtual Machine (JVM) translates and executes java byte code

Question: – What is Byte Code?
Answer: – Java compiler generates byte code for all the Java code and converts into class files.

Question: – What is JDK?
Answer: – Java Development Kit (JDK) is a superset of the JRE and includes compilers and debuggers tools with JRE required for developing Java applications.

Question: – Differentiate between the Path and Classpath?
Answer: – Path = defines the location where the system can look up for the executables (.exe) files.
Classpath = specifies the location of the Java class files.

Question: – Differentiate between a constructor and method?
Answer: – Constructor = Gets automatically invoked to create an object
Method = Gets called explicitly

Question: – Is it permissible for a constructor to have a different name than its class name in Java?
Answer: – No. Name of constructor is always same with its class name

Question: – Differentiate between an argument and a parameter?
Answer: – In methods definition, we pass variables which we can refer as parameters. And when we call these methods and pass values for the variables then they are phrased as arguments.

Question: – What will happen if you declare the main method as private?
Answer: – Program will get compiled correctly but will throw the error “Main method not public.” at runtime.

Question: – Difference between pass by reference and pass by value in Java?
Answer: – Pass by reference = Passing the address itself rather than passing the value.
Pass by value = Giving a copy of the value.

Question: – Can you compile a Java class successfully without having the main method?
Answer: – Yes, we can compile, but it won’t run

Question: – Is Java program will compile/run if we use <static public void> instead of <public static void>?
Answer: – Yes, the program will compile and run as usual.

Question: – What is meaning of public static void main (String args [])?
Answer: – Public- main ():- Entry point method which the JVM calls when a program is run. It is mandatory to get accessible from the Java environment.
Static- JVM must be capable of calling this method without creating an instance of the class.
Void- main ():- Doesn’t return anything so its return type must be void.
Argument string represents the argument type passed from the console, and the ‘args’ is an array of strings specified at the command line.

Question: – Does java support multiple inheritance?
Answer: – No

Question: – Can we declare class as a protective?
Answer: – No

Question: – What is package?
Answer: – It is collection of related classes and interfaces

Question: – Can class be defined inside an interface?
Answer: – Yes

Question: – Can interface extend another interface?
Answer: – Yes

Question: – Can interface defined inside a class?
Answer: – Yes

Question: – What is encapsulation?
Answer: – Wrapping code and data together into a single unit is called as encapsulation. All data members are private in fully encapsulated class.

Question: – Can we overload main method?
Answer: – Yes. It always runs first main method only

Question: – What are the naming conventions?
Answer: – Class name = should start with upper case letter
Interface name = should start with upper case letter
Method name = should start with lower case letter
Variable name = should start with lower case letter
Package name = should start with lower case letter
Constant name = should start with upper case letter
CamelCase = if name combined with two words then second name start with upper letter

Question: – What is instance variable?
Answer: – A variable which created inside the class but outside the method is known as instance variable. At compile time instance variable doesn’t get memory but gets memory at run time

Question: – What is new keyword?
Answer: – The new keyword is used to allocate memory at the time of run time

Posted by Kumar in Selenium, 0 comments

What is Page Object Model (POM) in Selenium

What is Page Object Model (POM) -:
Page Object Model (POM) is a just design pattern not a framework in Maven used to create object repository for web UI elements. It is API to drive and interact with UI. Web page contains multiple pages one inside the other. Each web page corresponds to separate class. All pages of your AUT are mapped to a class file in your code and each method within the class file can be treated as a service offered by the POM.                                                                                                              An implementation of the POM can be achieved by separating the abstraction of the test object and the test scripts.

POM make non-brittle test code and reduce or eliminate duplicate test code building directory, which is target; the source directory, which is src/main/java; the test source directory, which is src/test/java to avoid duplication.

It improves the readability and allows us to create interactive documentation.

Advantages of POM -:
1] Script will be cleaner and more readable format
2] It is easy to understand
3] Easy to maintain
4] Easy to reusable
5] Simple to Mapping

POM Implementation -:
It can be implemented with the help of following two ways -;
I] Using normal approach
II] Using page factory and @FindBy

POM Design Structure -:
-PomwithTestNG  // Maven Project name
+JRE System Library[J2SE-1.5]
+Maven Dependancies

Posted by Kumar in Selenium, 0 comments

Selenium Interview Questions and Answers for Experienced

Que.1] What is Selenium?
Ans -: It is automated tool used to automate only web based application. It support functional and regression testing.

Que.2] For which operating system (OS) selenium support
Ans -: MS Window, Linux, Macintosh

Que.3] For which browser selenium support etc
Ans -: Firefox, Internet Explorer, Safari, chrome etc.

Que.4] Which language selenium support?
Ans -: To enhance the automated test cases Java, C#, PHP, Python, Perl, Ruby etc.are used. Java is most used used in automated testing.

Que.5] When selenium was launched?
Ans -: Selenium was launched in 2001.

Que.6] When selenium webdriver was launched?
Ans -: Selenium webdriver was launched in 2006.

Que.7] When Selenium 2 is launched?
Ans -: Selenium 2 was launched in 2008. It is merged with webdriver and RC

Que.8] Which are the part of Selenium 1?
Ans -: Selenium 1 consist IDE (Integrated Development Environment), RC and selenium grid

Que.9] Which are the part of Selenium 2?
Ans -: Selenium 2 consist IDE (Integrated Development Environment), RC (Remote Control), Webdriver and selenium grid

Que.10] How much Selenium cost?
Ans -: Selenium is open source, can download free of cost from seleniumhq website. It is license with Apache 2.0

Que.11] What are the selenium component or selenium tools?
Ans -: Selenium components are IDE, RC, Webdriver and Grid

Que.12] What is Selenium IDE and how it works?
Ans -: IDE is a tool to create and execute test cases. It has record and playback feature

Que.13] What are the features of selenium IDE?
Ans -: Record and playback test cases, execute group of test cases (test suit) and edit test script

Que.14] What are the drwaback of selenium IDE?
Ans -: It supports only Mozila Firefox not other browsers. It doesn’t support flow control statement, programming language and complicated programs. It doesn’t support random test cases

Que.15] What is data driven test cases?
Ans -: Data driven test cases means executing test cases using multiple test case data

Que.16] What is selenium RC (Remote Control)?
Ans -: Rc support execution of test cases and multiple languages like java, c#, perl, php, python etc. It support random test cases. It support varius browser and flow control and control program

Que.17] What are the disadvantages of RC
Ans -: It is tekes more time to execute test cases. It doesn’t support parallel execution.

Que.18] Whar is selenium webdriver/
Ans -: Slenenium webdriver support execution of test cases and multiple languages like java, c#, perl, php, python etc. It support varous programming interface and operating environemnt. It support data driven test cases. Also support cross browset testing. It is faster than than other selenium suit.It support parallel test cases link TestNG. It provides summary only

Que.19] What is element locator?
Ans -: Element locator in selenium is used to locate elements or objects from web page

Que.20] What is selenium grid?
Ans -: Selenium grid used only test execution. It is not used to test design. It helps to run parallel test case execution in different RC. It helps to reduce time

Que.21] What is the difference between selenium and UFT (QTP)?
Ans -: Selenium is open source. It support multiple browser.It support various programming and scripting language. It requires install firebug and fire path plugins to inspect elements.
UFT is vender tool (license tool). It support only MS window.It support VB script only. It has built in object spy to inspect elements.

Que.22] What are the testing framework used in selenium/
Ans -: Junit (helps to execute test batches and generate test report) and TestNG (used to execute test suite and parallel testing).

Que.23] How to configure selenium?
Ans -: a] Download and install java software
b] Dowload and extract IDE
c] Download and install firbug and fire path plugins for firefox browser to inspect elements
d] Download selenium webdriver

Posted by Kumar in Interview Questions, Selenium, 0 comments

Frame in Selenium Webdriver

What is Frame -:
A webpage / page of any application contain number of elements. These elements may present in different frames. Frame in selenium webdriver is a HTML documents embedded inside another HTML documents. Also web pages can be embedded in another web page.
<frame1> </frame1>
<frame2> </frame2>
<frame3> </frame3>

It is also called as Inline Frame (Iframe).

Main (Default) Page Content

This is left frame This is mid frame This is right frame

How to identify frames in selenium WebDriver-:
In web pages it is not easy to detect frames in web page.In Selenium to work with Iframe / Frames, we have different ways to identify frame depending on the need. Following are the ways of identify frames
A] While inspecting the HTML code of web page then get to know how many frames in web page

<html webdriver = “true”>

<frameset border=”0″ framespacing=”0″ frameborder=”NO” cols=”25%,*,25%”>
<frame id=”left” src=”frame_a.htm”></frame>
<frame src=”frame_b.htm”></frame>
<frame src=”frame_c.htm” name=”right”></frame>


B] Click on element of web page
1] Right click on the element then will get whether frame is there or not. If frame option is present it means web page contains frame.
2] Select frame information according to requirement Iframe.


How to handle frames in selenium WebDriver-:
We can handle and switch over the elements in frames using 3 ways.
– By Index
– By Name or Id
– By Web Element
driver.switchTo().defaultContent();           // Deafault or main
driver.switchTo().frame(“left”);                  // left indicates id
driver.switchTo().frame(2);                       // 2 indicates index
driver.switchTo().frame(1);                       // 1 indicates index

How frame works in selenium WebDriver -:
How to switch to frames in selenium webdriver -:
If there are three frames in webpage in default contents then
1] If we are working in first (left) frame and once finished the work then have to switch in default contents of web page using
                                    driver.switchTo().defaultContent();     // Switching to default content

2] Work same like first frame

3] Work same like first or second frame

After work done of respective frame, then have to switch in default which main content and then go to next frame where you want to go from default or main page.

Example -:
Based on
package Element;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class frame {

public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.switchTo().frame(“left”); // indicates frame 1
String lefttext = driver.findElement(By.tagName(“p”)).getText();
driver.switchTo().defaultContent(); // Switch to default (main)
driver.switchTo().frame(2);             // indicates frame 3
driver.findElement(“name”)); // “name” indicates by value
String righttext = driver.findElement(By.tagName(“p”)).getText();
driver.switchTo().defaultContent();     //Switch to default (main)
driver.switchTo().frame(1);                // indicates frame 2 by “id”
String mid = driver.findElement(By.tagName(“p”)).getText();

Output -:

This left frame                      This is mid frame                         This is right frame
Posted by Kumar in Selenium, 0 comments

what is xpath in Selenium

What is X Path -:
X Path is a unique path of the element. In any website or web based application contains number of web elements / objects like text field, button, radio button, drop box, link, image etc. This object has unique id or path. If there are common attributes and values then X path is designed to allow the navigation of XML documents with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing.

It is used to find the location of any element on a webpage using HTML DOM structure.

It is used mostly to identify exact field among the common attributes and values.

X Paths are derived from the html paths of the objects; it can install firebug, and on the top of firebug install fire path in Mozilla.

At the times X Path generated by Firebug are too complicated and you see there is a possibility of getting a shorter XPath. Based on generated X path it is divided into two types viz.
1] Relative path
2] Absolute path
1] Relative path -:
A relative x path finds the closed id to the DOM element and generates x path starting from that element (middle).

It always starts with ‘double slash’ (/’/’), which means that it can search matching element anywhere form the webpage.

No need to write long path (as start from middle).

A ‘double slash’ (‘//’ ) signifies to look for any child or any grand-child element inside the parent.

Syntax -:
We can write relative x path = //tagname[@attribute=’value’]
// – Is a relative path start from middle or matching element
tagname – Is a Starting name of tag e.g input, div etc.
attribute – Is a name of attribute e.g. id, name, value etc.
value – Is a attribute value e.g. 12, Kumar etc

2] Absolute path -;
It indicates with complete path from the Root Element to the desire element.

It starts with ‘single slash’ (/’’), which means that it can start form root node of the webpage.

Needs to write long path (as starts from root node)

As it is direct way to find the element, but the disadvantage is that if there are any changes made in the path of the element then that x path gets failed.

Syntax -:
We can write relative x path = /html/body/div[2]/div/div
/ – Is a absolute x path starting from root node
body – Element in a body
div – Is a starting node (matching or identify)
[2] – Position of element e.g. [2] indicates 2 number element from div

Which is mostly used among the Relative and Absolute X path -:
It is always better to choose Relative xpath, as it helps us to reduce the chance of element not found exception.
In absolute x path if there are any changes made (webelements when added/Removed) in the path of the element then that x path gets failed

Posted by Kumar in Selenium, 0 comments

How Selenium WebDriver Works

Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change without the page itself being reloaded. WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.

Selenium webdriver was released as a part pf selenium 2.0 to overcome selenium 1.0 or selenium RC limitations like
– Issues working with pop-ups
– Dialogs
– Multiple browser
– File upload and download

It is an object oriented as compared to selenium 1.0 in terms of working with webelement, windows, dialogs by creating object.

It is designed in simpler and better way for modern web application and uses browser native command to drive the browser.

It support multiple browser, operating system and programming language

WebDriver works as an interface which used to drive / call the browser (Firefox, Chrome, IE etc) using each browsers native supports for automation.

WebDriver will run the browser directly.

Example -:
package Element;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class browser {

public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.findElement(“lst-ib”)).sendKeys(“WebDriver in Selenium”);


In result some elements works like -:
WebDriver driver = Create WebDriver instance
FirefoxDriver() = Implement Firefox browser
import org.openqa.selenium.WebDriver = Import WebDriver driver form other class for use
import org.openqa.selenium.firefox.FirefoxDriver = import Firefox driver from other class for use
WebDriver driver = new FirefoxDriver() = Open Firefox
driver.get(“”) = Open home page
driver.findElement(“lst-ib”)).sendKeys(“WebDriver in Selenium”) = Type in Google search box “WebDriver in Selenium”
driver.close() = Close the Firefox window

From the above code, will get results in the form of -:
– Firstly open the Google home page in Firefox browser
– Write WebDriver in Selenium in Google search engine
– Close the Firefox browser

Posted by Kumar in Selenium, 0 comments

Advantages and Disadvantages of Selenium

Selenium is the most powerful open source automation tool. It is developed by Jason Huggin under the Apache 2.0 and can be downloaded and used without any charge. Selenium is easy to get started with for simple functional testing of web application and support multiple operating system and browser. Selenium is also popular to automate, web-based administrative tasks and following are the advantage and disadvantage of selenium tool to automate testing process.

Test automation process has specific advantages for improving the long-term efficiency of testing processes. Test automation supports:
– Frequent regression testing
– Support rapid feedback to developers
– Virtually unlimited iterations of test case execution
– It support for Agile and extreme development methodologies
– It is disciplined documentation of test cases
– It support customized defect reporting
– Used where finding defects missed by manual testing

Advantages -:
1. Selenium is open source, freeware and portable tool.

2. It supports variety of languages that include Java, Perl, Python, C#, Ruby, Groovy, Java Script, and VB Script. etc.

3. Supports multiple operating systems like Windows, Macintosh, Linux, UNIX etc.

4. It supports multiple browsers like Internet explorer, Chrome, Firefox, Opera, Safari, HtmlUnit etc.

5. It can be integrated with other framework for source code compilation

6. It can be integrated with testing framework for testing our applications and generating reports.

7. It can be integrated with Jenkins or Hudson for continuous integration.

8. It can be used for Android, IPhone, Blackberry etc. based application testing.

9. It supports very less CPU and RAM consumption for script execution.

10. It integrates well with popular tools such as Hudson, SauceLabs, Selenium-Grid, QMetry and others for reporting, build system or any other aspect of their testing framework their testing framework

11. It provides record / playback tool for authoring tests without learning test scripting language.

Disadvantages -:
1. Selenium needs very much expertise resources.

2. It only supports web based application and does not support windows based application.

3. It is difficult to test Image based application.

4. It need outside support for report generation activity.

5. It does not support built in add-ins support.

6. It does not provide any built in IDE for script generation and it need other IDE like Eclipse for writing scripts.

7. It is not complete or compressive solution for automate testing web application

8. It has no test management facilities.

Posted by Kumar in Selenium, 0 comments

Compare IDE vs RC vs WebDriver vs Grid in Selenium

In a competitive era, selenium tool used to automate different type of web based application in different browser. For automation and regression testing selenium tool plays vital role. Selenium is a set software package which includes Remote Control (RC), Integrated Development Environment (IDE), WebDriver and Grid to make effective, interactive and responsive web application.

Difference between RC vs IDE vs WebDriver vs Grid in selenium point out the exact role in the automation tool. Following are the key points to compare selenium RC vs IDE vs WebDriver vs Grid.

S.N Focus Area IDE RC WebDriver Grid
1 Browser Support or works on only Mozilla Firefox Support all browser like IE, Mozilla Firefox, Chrome, Opera etc. Support all browser like IE, Mozilla Firefox, Chrome, Opera etc. with latest version Support all browser like IE, Mozilla Firefox, Chrome, Opera etc. with latest version
 2  OS  Support to all OS  Support to all OS  Support to all OS  Support to all OS
 3  Record and Playback  Support to record and playback  Doesn’t support record and playback  Doesn’t support record and playback
4 Server Doesn’t require to start execution Server is required to start execution Doesn’t require to start execution Server is required to start and support different test  execution
5 Core Engine Core Engine is Java script based Core Engine is Java script based Interact with browser
6 Plug-in It is GUI plug-in It is standalone Java plug-n It is API which binds various languages
7 Use Simple to use Simple and small Complex and bit large
8 Object Oriented It is not object oriented It is less object oriented Purely object oriented
9 Mouse Cursor It doesn’t support moving Mouse Cursor It doesn’t support moving Mouse Cursor It support moving Mouse Cursor
10 Listener Not support to listener Not support to listener Support to listener
11 Append xpath Need to append full xpath Need to append full xpath No need to append full xpath
12 iPhone / Android application Doesn’t support iPhone / Android application Doesn’t support iPhone / Android application Support iPhone / Android application


Posted by Kumar in Selenium, 0 comments