Selenium Java Interview Questions
Selenium Java Interview Questions
Selenium Java Interview Questions
WORLD
www.thetestingworld.com
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
Selenium IDE
Selenium RC
Selenium WebDriver
TESTING
WORLD
www.thetestingworld.com
Firefox
FirefoxDriver driver = new FirefoxDriver();
Chrome Driver
System.setProperty("webdriver.chrome.driver", "path of chrome driver executable");
ChromeDriver driver = new ChromeDriver();
IE Driver
System.setProperty("webdriver.ie.driver", "path of ie driver executable");
InternetExplorerDriver driver = new InternetExplorerDriver();
Supported in Webdriver
Supported in RC
Id
findElementById
id=
Name
findElementByName
name=
Identifier
Not Available
identifier=
Link
findElementByLinkText
findElementByPartialLinkText
link=
CSS
findElementByCssSelector
css=
DOM
Not Available
dom=
XPATH
findElementByXpath
xpath=//
Class Name
findElementByClassName
class=
Tag Name
findElementByTagName
Not available
What is Annotation
Annotation can be defined as metatag, which holds information about methods which are placed next to it.
Unit Testing tool like Junit and TestNg support Annotations
Annotations in Junit
@Test
@Test (timeout=500)
@Test(expected=IllegalArgumentException.class)
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
@Before
: Will execute before every @Test Annotation
@After
: Will execute after every @Test Annotation
@BeforeClass
: Will execute before executing any other annotation, execute only once at the start
@AfterClass
: Will execute after executing all other annotation, execute only once at the end
@Ignore : Used with @Test annotation, will skip execution of particular test method
@Parameterized : Used for running my test case with multiple data
Order of Execution
@BeforeClass @Before @Test @After @AfterClass
Order of Execution
@BeforeSuite @BeforeTest @BeforeGroup @BeforeClass --> @BeforeMethod @Test
@AfterMethod @AfterClass @AfterGroup @AfterTest @AfterSuite
Junit
Support annotation
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
Navigate() method
driver.navigate().to("http://rediff.com");
driver.navigate().back();
driver.navigate().forward();
1 Thread.sleep(10)
Thread is a java class, we are calling sleep method of that class
It will add a forcefully wait at particular point
This is used when we want to always pause our execution at specific point
2 ImplicitWait
Implicitly wait are mainly used when our element on page are taking some time to load
It we dont add any wait in our script, then our driver will search for element and if not found immediately
failed that step
In case of implicitly wait, our driver will wait for specified time(time mentioned in implicitly wait) for that
element to be present
This wait will be applicable for findElements commands only
This need to placed at the start of test case, will be applied on all findElements commands
FirefoxDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
3 Explicit Wait (WebdriverWait class)
Explicitly wait (WebdriverWait class), is mainly used when we want to wait in script until a specified condition
is satisfied or max timeout we have given
FirefoxDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.textToBePresentInElement(By.id("f_id"), "Hello"));
4 Fluent Wait
It implements Wait interface and we create object of FluentWait class
Here we can set maximum time we should wait for element to be present(withTimeout method)
Here we can set after how much time, it will check for element to be present (pollingEvery method)
Here we can ignore any exception if it comes at runtime while waiting (ignoring method)
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
Selenium WEBDRIVER
// To Work on dropdown or List we need to create object
of Select class
Select dateselect = new
Select(driver.findElementById("f_mydata"));
Selenium RC
// Working with List
selenium.addSelection("ElementLocator", "Value");
// Working with Dropdown
selenium.select("ElementLocator", "Value");
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
In selenium, first we pick element locator of all elements on which we are supposed to perform our action and
place in a property file(Here property file behave as Object Repository for Selenium)
Now wherever in our test case, element locator value is required. We fetch element locator value from
properties file (this is called properties file because extension of this file is .properties)
To fetch value of element locator from property file, we need to create object of ResourceBundle class and
by that object we can use getString method.
What are Desired Capabilities?
Desired Capabilities help to set properties for the Web Driver. A typical use case would be to
set the path for the Firefox Driver if your local installation doesn't correspond to the default
settings.
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.PROXY, proxy);
How to perform Keyboard and Mouse Operations in Selenium
Or
How to Handle Page onLoad Authentication
For attachment and downloading we need to perform some keyboard or mouse operations, for that we have
few options in Selenium
1. Through ROBOT Class of JAVA
POM refers to Page Object Model which encapsulate the internal state of a page into a single page
object. UI changes only affect to a single Page Object, not to the actual test codes.
Advantages :
Code re-use: Able to use the same page object in a variety of tests cases.
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
What is WebDriverBackedSelenium ?
WebDriverBackedSelenium is a kind of class name where we can create an object for it as below:
Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, "URL ")
The main use of this is when we want to write code using both WebDriver and Selenium RC, we
must use above created object to use selenium commands.
How to get the number of frames on a page ?
List <WebElement> framesList = driver.findElements(By.xpath("//iframe"));
int numOfFrames = frameList.size();
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
When we compile java code, it convert java file to byte code (class file) rather than machine code,
byte code is machine and platform independent (.class file). We can interpret these class file to any
machine having JVM, JVM is used to interpret class file and convert it to machine dependent code
and then execute it.
What are different types of access modifiers?Access modifiers are used while creating class, method or variable.
public:
Any thing declared as public can be accessed from anywhere.
private: Any thing declared as private can be accessed inside class only cant be seen outside of its class.
protected:
Any thing declared as protected can be accessed by classes in the same package and
subclasses in the other packages.
Default :
Can be accessed only to classes in the same package.
What is Garbage Collection and how to call it explicitly?When an object is no longer referred to by any variable, java/JVM automatically reclaims memory used by that
object. This is known as garbage collection.
System. gc() method may be used to call it explicitly.
String
String Class is immutable
object cannot be modified (all
changes that we are
doing(uppercase, lowercase,
substring etc) on string object,
is creating a new string object
and old data still persist and
become garbage(lot of garbage
is generating, impact on
performance)
StringBuffer
StringBuffer is mutable
StringBuilder
StringBuilder is mutable
StringBuffer is thread
safe(synchronized) but slow
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
Static keyword in Java can be used with variable, method and nested class(class inside another class)
static variable: static variable holds single memory location independent to number of objects we have created,
all objects will access data from same memory location.
static methods: static methods are like static variable holds single memory location for all objects.
STATIC methods/variable can be called by the class name itself without creating object of the class
Static nested class object created without creating object of its outer class
Methods, variables which are not static is called instance variable/methods
Super keyword in Java
Super keyword in java is used to call parent class override method or parent class constructor
Super Class Method Calling
1--> In case child class override, parent class method. When we create child class object and call override
method it will access child class method but if we want to access parent class method, we are going to use
super keyword
Super Class Constructor Calling
2--> super keyword is used to call parent class constructor as well
Difference between :`
Abstract Method
Methods which are just declared not defined or
method without body.
Abstract Class
Concrete Method
Methods which are declared and defined as well or
method with body.
Concrete Class
Abstract Class
Interface
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
Inheritance
With the help of inheritance we can transfer the properties of a class to another class
Class which is inherited is called Parent Class or Super Class
Class which inherit other class is called Child Class or Sub Class
After inheritance, child class objects can access parent class method and variables .
extends is the keyword which is used to inherit class
implements is the keyword which is used to inherit interface
Type of Inheritance
Single/Simple
Inheritance
Supported in Java
Multilevel Inheritance
Supported in Java
www.thetestingworld.com
Multiple Inheritance
Hybrid Inheritance
TESTING
WORLD
www.thetestingworld.com
Constructors
Constructor can be defined as a group of code (same like method) which is used for initialization
Initialization means anything that we want to perform at start
Points to remember: Constructor name is always same as class name
Constructor does not return any value so we dont write void while creating constructor
Constructors are automatically called when object is created we need not to call them explicitly as we
do in methods( as constructor is automatically called when object is created so all code pasted inside
constructed is executed before we use class object to call any other methods, thats why it is called
initialization)
We can have more than 1 constructor in a class with different signature, this is called constructor
overloading
Exception handling in Java
1>> throws keyword : we can place throws keyword in front of our method definition and we can mention
classes of all exception which we want to handle or we can mention parent class Exception
2>> Try catch -- finally block
Code that can throw exception, need to be placed in try block
After getting exception, whenever the action we want to perform will be placed in catch block
If we want to perform some task at the end does not matter exception came or not we will paste that code in
finally block
We can use
try block then catch block
try block then finally block(we can skip catch block)
try block then catch block then finally block
Difference between Throw and Throws in Exception handling
1--> Throws is used in Method Signature while Throw is used in Java Code (send the instance of Exception class)
2--> Throws, we can mention multiple type of exception, separated by comma while in throw we can set only 1
exception class instance
3-->Throws keyword just throws exception need not to handle it, throw pass exception instance to caller
program
final :
final keyword can be used for class, method and variables.
A final class cannot be inherited, a final method cant be override.
A final variable becomes constant, we cant change its value
finally :
finally, keyword used in exception handling.
It is used with a block of code that will be executed after a try/catch block has completed
The finally block will execute whether or not an exception is thrown.
Means if exception is not throws then Try execute then Finally will execute, in case when exception is thrown
finally will execute after catch e
Example : Like we have written DB connection code in try block but exception comes
In that case connection persist with DB and no other user are allowed to create connection, So in that kind of
scenario we want whatever the condition comes, may be exception or not, my DB connection should break,
for that Ill paste connection breaking code in finally() block
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
finalize() : finalize() method is used to code something that we want to execute just before garbage collection
is performed by JVM
Generic Method/ Classes in Java
Collection is a interface, which gives architecture to hold multiple data by same name
In JAVA, Collection interface is implemented by Set, List and Map
SET
LIST
MAP
Array
ArrayList
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
Answer: Iterating to List and Set is very simple but in case of HashMap we have to use an extra method
"keySet" which pass hashmap object to Iterator
package mypack;
import java.util.HashMap;
import java.util.Iterator;
import org.junit.Test;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class MyClas {
public static void main(String aa[]){
HashMap hp = new HashMap();
hp.put("K1", "Val1");
hp.put("K2", "Val2");
Iterator itr= hp.keySet().iterator();
while(itr.hasNext()){
String k = itr.next().toString();
System.out.println(hp.get(k));
}}}
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
}}}
Print * Triangle
****
***
**
*
package mypack
public class MyClas {
public static void main(String aa[])
{
int i,j,k
// Here First loop is created for switching
line
for(i=0i<=5i++)
{
// Here this loop is created for
printing spaces in every line
for(j=0j<=ij++)
{
System.out.print(" ")
}// inner for loop close
// Here this loop is created for
printing * in every line
for(k=5k>=ik)
{
System.out.print(" * ")
}// inner for loop close
System.out.println("")
// Here we are switching to next
line after printing *
}// outer for loop close
}}
Search Integer element in Array
package mypack
public class MyClas {
public static void main(String aa[])
{
int i,j,k
for(i=0i<=5i++)
// Here First loop is created for switching
line
{
for(j=0j<=2j++)
// Here this loop is created for
printing spaces in every line
{
System.out.print(" ")
}// inner for loop close
for(k=0k<=ik++)
// Here this loop is created for
printing * in every line
{
System.out.print(" * ")
}// inner for loop close
System.out.println("")
// Here we are switching to next
line after printing *
}// outer for loop close
}}
Sorting an Array
package mypack
public class MyClas {
public static void main(String aa[])
{
int datatofind=6, flag=0
int[] i={2,4,6,78,6,7}
for(int j=0j<i.lengthj++)
if(i[j]==datatofind){
flag=1
System.out.println("Element
exist in system at index "+ j)
break
}// if close
if(flag==0)
System.out.println("Element is not
package mypack
public class MyClas {
public static void main(String aa[]){
int datatofind=6, flag=0
int[] i={2,4,6,78,6,1}
for(int j=0j<(i.length)j++) {
for(int k=j+1k<(i.length)k++ ){
if(i[j]>i[k])
{
i[j]=i[j]+i[k]
i[k]=i[j]i[k]
i[j]=i[j]i[k]
}}}
System.out.print("Sorted List ")
for(int j=0j<(i.length)j++)
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
found")
}}
Fabonacci Series upto 100
}}
Check a number is prime or not
package mypack
public class MyClas {
public static void main(String aa[])
{
// Fabonnaci series upto 100
// Fabonacci Series 0,1,1,2,3,5
(next number = add of last 2 numbers)
int a=0,b=1,z=0
System.out.print(a + " , " + b )
while (z<100)
{
z=a+b
a= b
b=z
if(z<=100)
{
System.out.print(", "+z)
}
}
}
}
package mypack
public class MyClas {
public static void main(String aa[])
{
int i=23, m
// Here i is the number which we want to
test is prime or not
int flag=0
for(int j=2j<(i/2)j++)
{
m=i%j
if(m==0)
{
System.out.println("This
is not a prime number,
divided by " +j)
flag=1
break
}
}// for loop close
if(flag==0)
{
System.out.println("This is a
prime number")
}
}}
Check Palendrome
package mypack
public class MyClas {
public static void main(String aa[])
{
String a="nitin"
String b=""
int k = a.length()
for(int i=(k1) i>=0i)
b=b+a.charAt(i)
if(a.equals(b))
System.out.println("Palendrome")
else
System.out.println("Not palendrome")
}//main () close
}// class close
TESTING
WORLD
www.thetestingworld.com
Reverse a String
package mypack
public class MyClas {
public static void main(String aa[])
{
String a="Hello World"
String b ="llo W"
int flag=0, lenb= b.length()
try{
for(int j=0j<(a.length()b.length())j++){
if(a.charAt(j)==b.charAt(0))
{
String sub1= a.substring(j,(j+lenb))
if(b.equals(sub1))
{
flag=1
System.out.println("Sub String is
Found")
break
}// inner if close
}// outer if close
}// for loop close
if(flag==0)
System.out.println("Substring not
found")
}// try block close
catch(Exception ex){
System.out.println(ex.getMessage())
}
}}
Search Element in String Array
Logic 1:
package mypack
public class MyClas {
public static void main(String aa[])
{
String a="Hello World"
int x=a.length()
System.out.println(x)
// display length of string
for(int j=0j<(x)j++)
System.out.print(a.charAt((xj1)))
}}
Logic 2:
package mypack
public class MyClas {
public static void main(String aa[])
{
String a="Hello World"
String b=""
int x=a.length()
System.out.println(x)
// display length of string
for(int j=0j<(x)j++)
b=b+a.charAt((xj1))
System.out.println(b)
}}
Sorting of String Array
public class Case1 {
public static void main(String aa[]) throws
AWTException{
int i,j
String[]arrString={"Nitin","Amit","Sumit","Kapil"}
for(i=0i<(arrString.length1)i++){
for(j=(i+1)j<arrString.lengthj++){
if(arrString[i].compareTo(arrString[j])>0)
{
String s=arrString[i]
arrString[i]=arrString[j]
arrString[j]=s
}
}
}
for(i=0i<(arrString.length)i++)
TESTING
WORLD
www.thetestingworld.com
System.out.println("Element is not
found")
}}
System.out.println(arrString[i])
}}
www.thetestingworld.com
TESTING
WORLD
www.thetestingworld.com
www.thetestingworld.com