0% found this document useful (0 votes)
28 views45 pages

Selenium Question2

The document contains a collection of Java and Selenium interview questions and answers, covering topics such as the Fibonacci series, singleton design pattern, framework components, and Java concepts like JDK, JRE, and JVM. It also discusses practical coding examples and the differences between various Java features, such as HashMap vs Hashtable and pass by reference vs pass by value. Additionally, it includes insights on OOP principles and the importance of wrapper classes in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views45 pages

Selenium Question2

The document contains a collection of Java and Selenium interview questions and answers, covering topics such as the Fibonacci series, singleton design pattern, framework components, and Java concepts like JDK, JRE, and JVM. It also discusses practical coding examples and the differences between various Java features, such as HashMap vs Hashtable and pass by reference vs pass by value. Additionally, it includes insights on OOP principles and the importance of wrapper classes in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Java Interview Questions

upper case every first letter of every word

String source = "hello good old world";


StringBuffer res = new StringBuffer();

String[] strArr = source.split(" ");


for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);

res.append(str).append(" ");
}

System.out.print("Result: " + res.toString().trim());

SeleniumForSure 1 Bipin Thakare | 7798452716


Java Interview Questions

Fibonaccy series
======================
(Infosys)

In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8,
13, 21, 34, 55 etc. The first two numbers of fibonacci series are 0 and 1.

public class fibonacciSeries {

public static void main(String[] args) {


// fibonacy series till 10

int a=0;
int b =1;
int sum;

System.out.print(a+" "+b); //printing 0 and 1

for(i=0; i<10; i++)


{
sum= a+b;
System.out.print(" "+sum);
a=b; //1
b=sum; //1
}
}

SeleniumForSure 1 Bipin Thakare | 7798452716


Selenium Interview Questions

Framework Interview Questions

Question :- What framework you have used in your current Project?


(HCL, Synechron, TCS, Capgemini, KPIT, TechM, Persistent, Zensar)
Ans :- We have used TestNG as a unit testing framework with Data
driven approach & design pattern used is Page Object Model

Explain the structure of your framework? (Accenture, deutsche bank,


master card, Synechron, ABB )
Ans :- Please refer to the framework notes

Q> What is singleton design pattern? (GE, Avaya, Mindtree, HCL)


Ans :-
in Java then you must have used new keyword. This new keyword
create an Object of class whenever required. But there are some
scenarios where you don’t want to create individual Object for different
purpose. Singleton Pattern ensures that one and only one Object is
instantiated for a given class. Whenever object of given class is
required, only single(No more than one object) Object get returned

we will create a private Constructor and also a static method to create


object of the same class.
class JBT {

private static JBT instance = null;

/*
* As private constructor is used so can not create object of this
class
* directly. Except by using static method of same class.
*/
private JBT() {

SeleniumForSure 1 Bipin Thakare | 7798452716


Selenium Interview Questions

/*
* This method will be used to get instance of JBT class. This
method will
* check if there is aready an object of class create or not if not
then it
* will create an Obect of JBT class and return the same else it will
return
* the existing Object.
*/
static JBT createInstance() {
if (instance == null)
return new JBT();
else
return instance;
}

int i;
}

Q>can you achieve Singleton design pattern using final? (NTT data,
deutsche bank)
Ans :- No

Q>How do you maintain version of your code? (Samsung, IBM, Syntel,


BMC)
Ans :- we use SVN to version our code. To do code check in and check
out we use subclipse

Q> What did you keep in excel and .properties? (Amazon, CG)

SeleniumForSure 2 Bipin Thakare | 7798452716


Selenium Interview Questions

Ans :- In Excel we keep all the data, such as multiple combination of


user names and password.
In properties file we keep xpaths, URL, default user name and password
etc.

Q> What are components of framework? (Media ocean, neeyamo, L


&T)
Or
Question :- Give me few points about what is the use of Framework
(jUnit or TestNg)

Ans :-
1. Reusability of code
2. Maximum coverage
3. Recovery scenario
4. Low cost maintenance
5. Minimal manual intervention
6. Easy Reporting

Q> How have you implemented OOPS in your project? Explain with
examples (Tieto, Fundtech)
Ans :- please refer to our designed framework

Question :- Have you tested in different browsers? If yes how? (Xnet,


Wipro, TechM)
ANS: yes, this can be done in 2 ways,
1) we can pass the browser names in Frame Work it self through
CONFIG.Properties file and
2) By using Grid we can test our application in multiple Browsers at a
time. This is called Parallel and First one is Sequential

SeleniumForSure 3 Bipin Thakare | 7798452716


Selenium Interview Questions

Question:- what are the issues you have faced while doing cross
browser testing?
Ans:- There is no issues with Firefox , But with IE and Chrome there is
an CERTIFICATION ERROR's.
Means if we are attempting to test an https sites these errors will
occer. So we have to override those errors with Desired Capabilities
class
2) This is easy but you should write, the Chrome and IE is not
independent browsers youknow these will come up with a driverexe
file you have to download these driverexe file according ur os
bit(64/32),
if ur system is 32 you have to download 32 bit driverexe file.. and you
have to specify the driver exe file Path in our program then only it will
work, other wise it will display an error.

Question:- Once a framework is developed will you do any changes to


the framework?
ANS: Yes. There could be few changes related to reports. There could
be few enhancement or changes in methods. The structure is same.

Question :- How frequently you execute your script? (In agile)


ANS: Every Day Dry Runs will be there, in order to confirm that all will
be working fine.

Question:- what are the components of framework?


Ans:- 1)General Frame work components: Properties files, configuration
files, Data sheets, Testbase class, Utilities Class, Test cases, Reports,
Logs

Question:- how to read the property files


Ans:-

Question:- How to read the excel files which API have you used

SeleniumForSure 4 Bipin Thakare | 7798452716


Selenium Interview Questions

Ans:- Apache POI

Question:- how do u take screen shot in your framework (Quest,


Wipro, accenture, persistent )
Ans:- we have created a library class and we were calling it in
@AfterMethod anotation
public static void ScreenShot(WebDriver driver,String screenshotName)
throws IOException
{
TakesScreenshot ts =(TakesScreenshot)driver;
File Source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(Source, new
File("./ScreenShots/"+screenshotName+".png"));
}

SeleniumForSure 5 Bipin Thakare | 7798452716


Java Interview Questions

JAVA Conceptual Questions

Q> what is JDK , JRE and JVM (VM ware, IBM, HCL)
Ans:-

Q> What is wrapper class and why do we need them or where do we use it (VM Ware,
symphony telca)
Ans:- Java is an object-oriented language and can view everything as an object. A simple file can
be treated as an object , an address of a system can be seen as an object , an image can be
treated as an object (with java.awt.Image) and a simple data type can be converted into an
object (with wrapper classes). Wrapper classes are used to convert any data type into an
object.
The primitive data types are not objects; they do not belong to any class; they are defined in
the language itself. Sometimes, it is required to convert data types into objects in Java
language. For example, upto JDK1.4, the data structures accept only objects to store. A data
type is to be converted into an object and then added to a Stack or Vector etc. For this
conversion, the designers introduced wrapper classes.
What are Wrapper classes?
As the name says, a wrapper class wraps (encloses) around a data type and gives it an object
appearance. Wherever, the data type is required as an object, this object can be used. Wrapper
classes include methods to unwrap the object and give back the data type. It can be compared
with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent
from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
Observe the following conversion.
int k = 100;
Integer it1 = new Integer(k);
The int data type k is converted into an object, it1 using Integer class. The it1 object can be used
in Java programming wherever k is required an object.

SeleniumForSure 1 Bipin Thakare | 7798452716


Java Interview Questions

The following code can be used to unwrap (getting back int from Integer object) the object it1.
int m = it1.intValue();
System.out.println(m*m); // prints 10000
intValue() is a method of Integer class that returns an int data type.

Importance of Wrapper classes


There are mainly two uses with wrapper classes.
1) To convert simple data types into objects, that is, to give object form to a data type; here
constructors are used.
2) To convert strings into data types (known as parsing operations), here methods of type
parseXXX() are used.
Features of the Java wrapper Classes.
1) Wrapper classes convert numeric strings into numeric values.
2) The way to store primitive data in an object.
3) The valueOf() method is available in all wrapper classes except Character
4) All wrapper classes have typeValue() method. This method returns the value of the object as
its primitive type.

Q> java Autoboxing and unboxing (HSBC)


Ans:- The automatic conversion of primitive data types into its equivalent Wrapper type is
known as boxing and opposite operation is known as unboxing. This is the new feature of Java5.
So java programmer doesn't need to write the conversion code.
Example:-

Q> what thing goes to heap and stack (sears, synechron, Sigma Edge)
Stack :- faster
Heap :- slow
All premetive data types and functions calls are stored on stack.
If object is created then only its reference is created on stack.
All non premetive data types such as string, arrays and objects are stored on heap

Q> what is the difference between hasmap and hastable (wipro, J & J, Talentica )
Ans :- There are several differences between HashMap and Hashtable in Java:

Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-
threaded applications, as unsynchronized Objects typically perform better than synchronized
ones.
Hashtable does not allow null keys or values. HashMap allows one null key and any number of
null values.
HashMap is not an ordered collection which means it does not return the keys and values in the
same order in which they have been inserted into the HashMap

SeleniumForSure 2 Bipin Thakare | 7798452716


Java Interview Questions

Code for HashTable

public class HashTableExample {


public static void main(String args[]){

Hashtable<Integer,String> ht=new Hashtable<Integer,String>();

ht.put(100,"pune");
ht.put(101,"mumbai");

System.out.println(ht.get(100));
System.out.println(ht.get(101));
}

Q> What is meant by pass by reference and pass by value in Java? (HSBC, IBM, Syntel)
Ans:- Pass by reference means, passing the address itself rather than passing the value. Pass by
value means passing a copy of the value.

Q> What is Byte Code? (sears,,bmc)


Or
What gives java it’s write once and run anywhere nature?
or
What makes Java Platform independent (bmc)
Ans:- All Java programs are compiled into class files that contain bytecodes. These byte codes
can be run in any platform
and hence java is said to be platform independent.

Q> Expain the reason for each keyword of public static void main(String args[])? (infosys, CTS,
PTC, Avaya, Wipro, Amdocs)
Ans:- public- main(..) is the first method called by java environment when a program is
executed so it has to accessible from java environment. Hence the access specifier has to be
public.
static: Java environment should be able to call this method without creating an instance of the
class , so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type and arg is an array for string given during
command line.

SeleniumForSure 3 Bipin Thakare | 7798452716


Java Interview Questions

Q> What are the differences between == and .equals() ? ( xpanxion, media ocean, cts, scale
arc, synerzip, talentica, Wipro, HCL, TechM, Mphasis, TCS)
Or
what is difference between == and equals
Or
Difference between == and equals method
Or
What would you use to compare two String variables, the operator == or the method
equals()?
Or
How is it possible for two String objects with identical values not to be equal under the ==
operator?
Ans:-
The == operator compares two objects to determine if they are the same object in memory i.e.
present in the same memory location.
It is possible for two String objects to have the same value, but located in different areas of
memory.
== compares references while .equals compares contents. The method public boolean
equals(Object obj) is provided by the Object class and can be overridden.
The default implementation returns true only if the object is compared with itself, which is
equivalent to the equality operator == being used to compare aliases to the object. String,
BitSet, Date, and File override the equals() method. For two String objects, value equality
means that they contain the same character sequence. For the Wrapper classes, value equality
means that the primitive values are equal.

Example:-
--------
public class EqualsTest {

public static void main(String[] args) {

String s1 = "abc"; //this may or


String s2 = s1;
String s5 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println("== comparison : " + (s1 == s5)); //== comparison : true
System.out.println("== comparison : " + (s1 == s2)); // == comparison : true
System.out.println("Using equals method : " + s1.equals(s2)); // true
System.out.println("== comparison : " + s3 == s4); //== comparison : false
System.out.println("Using equals method : " + s3.equals(s4)); // true

}
}

SeleniumForSure 4 Bipin Thakare | 7798452716


Java Interview Questions

Output
-----------
== comparison : true
== comparison : true
Using equals method : true
== comparison : false
Using equals method : true

Note :-
String a = "abc";

May or may not create a new String object.


If a String object with the literal "abc" already exists the reference 'a' will only point to it.
Since String objects are immutable.

Where as,
String a = new String("abc");
will always create a new Sting object.

Q> What if the static modifier is removed from the signature of the main method? (xpanxion,
synechron, 3i infotech, Aftek )
Or
What if I do not provide the String array as the argument to the method?
Ans:-
Program compiles. But at runtime throws an error NoSuchMethodError .

Q> What is the difference between final, finally and finalize? What do you understand by the
java final keyword? (bmc, infy, hsbc)
Or
What is final, finalize() and finally?
Or
What is finalize() method?
Or
What is the difference between final, finally and finalize?
Or
What does it mean that a class or member is final?
Ans:-
final – declare constant
finally – handles exception
finalize – helps in garbage collection

SeleniumForSure 5 Bipin Thakare | 7798452716


Java Interview Questions

Q> Describe the principles of OOPS ( synerzip, entity data, CTS, persistent, caterpillar, j&J,
synchrony, sunguard, cybage, bitwise )
Ans:- There are three main principals of oops which are called Polymorphism, Inheritance and
Encapsulation.

Q>Explain the Polymorphism principle. Explain the different forms of Polymorphism. ( all the
companies )
Ans:- Polymorphism in simple terms means one name many forms. Polymorphism enables one
entity to be used as a general category for different types of actions. The specific action is
determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method o erloadi g
• Method o erridi g through i herita e
• Method o erridi g through the Ja a i terfa e

Q> In System.out.println(), what is System, out and println? ( hsbc, sears, xpanxion, cybage)
Ans:- System is a predefined final class, out is a PrintStream object and println is a built-in
overloaded method in the out object.

Q> What are Java Access Specifiers? (allSccripts, talentica,Cybage)


Or
What is the difference between public, private, protected and default Access Specifiers?
Or
What are different types of access modifiers?
Ans:- Access specifiers are keywords that determine the type of access to the member of a
class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Prote ted : a essi le to the lasses ithi the sa e pa kage a d a y su lasses.
• Pri ate : a essi le o ly to the lass to hi h they elo g
• Default : a essi le to the lass to hi h they elo g a d to su lasses ithin the same
package

Q> Which class is the superclass of every class? (Symantec)


Ans:- Object.

Q> What is the difference between static and non-static variables? (all the companies)
Or
What are class variables?
Or
What is static in java?

SeleniumForSure 6 Bipin Thakare | 7798452716


Java Interview Questions

Or
What is a static method?
Ans:-
A static variable is associated with the class as a whole rather than with specific instances of a
class. Each object will share a common copy of the static variables i.e. there is only one copy
per class, no matter how many objects are created from it. Class variables or static variables are
declared with the static keyword in a class. These are declared outside a class and stored in
static memory. Class variables are mostly used for constants. Static variables are always called
by the class name. This variable is created when the program starts and gets destroyed when
the programs stops. The scope of the class variable is same an instance variable. Its initial value
is same as instance variable and gets a default value when its not initialized corresponding to
the data type. Similarly, a static method is a method that belongs to the class rather than any
object of the class and doesn’t apply to an object or even require that any objects of the class
have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object,
and static methods are attached to a class, not an object. A static method in a superclass can be
shadowed by another static method in a subclass, as long as the original method was not
declared final. However, you can’t override a static method with a non-static method. In other
words, you can’t change a static method into an instance method in a subclass.
Non-static variables take on unique values with each object instance.

Q> Can I have multiple main methods in the same class? (xorient, cts)
Ans:- We can have multiple overloaded main methods but there can be only one main method
with the following signature :
public static void main(String[] args) {}

Q> Does Java support multiple inheritance? (all the companies)


Ans :- No java does not support it. but there is a workaround. we can achieve it using
interfaces.

Q> What is constructor? (KPIT, tech M)


Ans:- Constructor is just like a method that is used to initialize the state of an object. It is
invoked at the time of object creation.

Q> Difference between method overloading and method overriding(all the companies)
Ans:-
Method Overloading
------------------
1) Method overloading increases the readability of the program.
2) method overlaoding is occurs within the class.
3) In this case, parameter must be different. In this case, parameter must be same.
Method Overriding
------------------

SeleniumForSure 7 Bipin Thakare | 7798452716


Java Interview Questions

1) Method overriding provides the specific implementation of the method that is already
provided by its super class.
2) Method overriding occurs in two classes that have IS-A relationship.
3) In this case, parameter must be same.

Q> Can we override static method? (Persistent, synechron)


Ans:- No, you can't override the static method because they are the part of class not object

Q> What is Runtime Polymorphism? (Persistent, CTS, techM, Vodafone)


Ans:- Runtime polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a super class.
The determination of the method to be called is based on the object being referred to by the
reference variable.

Q> What is difference between abstract class and interface? (all the companies)
Ans:-
Abstract class
--------------
1)An abstract class can have method body (non-abstract methods).
2)An abstract class can have instance variables.
3)An abstract class can have constructor **************
4)An abstract class can have static methods.
5)You can extends one abstract class.

Interface
---------
1)Interface have only abstract methods.
2)An interface cannot have instance variables.
3)Interface cannot have constructor.
4)Interface cannot have static methods.
5)You can implement multiple interfaces.

Q> Does Interfaces allows constructors?


Ans:-
 No. Interfaces does not allow constructors.
 Why interface does not have constructor? The variables inside interfaces
are static final variables means constants and we can not create object for
interface so there is no need of constructor in interface that is the reason
interface doesn't allow us to create constructor.

Q> Can we create static constructor in java (thoughtworks)

SeleniumForSure 8 Bipin Thakare | 7798452716


Java Interview Questions

Ans:-
 No. We can not create constructor with static.
 If we try to create a static constructor compile time error will come: Illegal
modifier for the constructor

Q> What is difference between Checked Exception and Unchecked Exception? (persistent)
Ans:-
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException,SQLException etc. Checked exceptions are checked at
compile-time.

2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at
compile-time.

Q>Is it necessary that each try block must be followed by a catch block? (infy,
techM,persistent,nuance)
Ans:- It is not necessary that each try block must be followed by a catch block. It should be
followed by either a catch block OR a finally block. And whatever exceptions are likely to be
thrown should be declared in the throws clause of the method.

Q>What is finally block? (infy,cts,techm)


Ans:-finally block is a block that is always executed

Q> What is difference between throw and throws? (persitent)


Ans:-
throw keyword
-------------
1)throw is used to explicitly throw an exception. throws is used to declare an exception.
2)checked exceptions can not be propagated with throw only. Un checked exception can be
propagated with throws.
3)throw is followed by an instance. throws is followed by class.
4)throw is used within the method. throws is used with the method signature.
5)You cannot throw multiple exception You can declare multiple exception e.g. public void
method()throws IOException,SQLException.

throws keyword
--------------
1)throws is used to declare an exception.
2)checked exception can be propagated with throws.

SeleniumForSure 9 Bipin Thakare | 7798452716


Java Interview Questions

3)throws is followed by class.


4)throws is used with the method signature.
5)You can declare multiple exception e.g. public void method()throws
IOException,SQLException.

Q> What is the difference between String, StringBuffer and StringBuilder ? (all the companies)
Ans:-
String:-
------
String is immutable ( once created can not be changed )object . The object created as a String
is stored in the Constant String Pool .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can
not be used by two threads simultaneously.
String once assigned can not be changed.
Example:-
String demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.

demo="Bye" ; //new "Bye" string is created in constant pool and referenced by the demo
variable
// "hello" string still exists in string constant pool and its value is not overrided but we lost
reference to the "hello"string

StringBuffer ( Thread safe)


---------------
StringBuffer is mutable means one can change the value of the object . The object created
through StringBuffer is stored in the heap . StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this it does not allow two threads to simultaneously access the same method . Each
method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to
thread safe property . Thus StringBuilder is faster than the StringBuffer when calling the same
methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its
a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.
Example:-

SeleniumForSure 10 Bipin Thakare | 7798452716


Java Interview Questions

StringBuffer demo1 = new StringBuffer("Hello") ;


// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder (Not a thread safe)


--------------
StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be
modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder
is not thread safe.
StringBuilder is fast as it is not thread safe .
Example:-
StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder

Q> What is the difference between abstraction & encapsulation? (Schlumberger)


Ans :-
Abstraction occurs during class level design, with the objective of hiding the implementation
complexity of how the the features offered by an API / design / system were implemented, in a
sense simplifying the 'interface' to access the underlying implementation.

For example, a Java developer can make use of the high level features of FileInputStream
without concern for how it works (i.e. file handles, file system security checks, memory
allocation and buffering will be managed internally, and are hidden from consumers). This
allows the implementation of FileInputStream to be changed, and as long as the API
(interface) to FileInputStream remains consistent, code built against previous versions will
still work.

Similarly, when designing your classes, you will want to hide internal implementation from
others as far as possible.

Encapsulation, often referred to as "Information Hiding", revolves more specifically around the
hiding of the internal data (e.g. state) owned by a class instance, and enforcing access to the
internal data in a controlled manner.

For example, class fields can be made private by default, and only if external access to these
was required, would a get() and/or set() (or Property) be exposed from the class. (In modern
day OO languages, fields can be marked as readonly / final / immutable which further

SeleniumForSure 11 Bipin Thakare | 7798452716


Java Interview Questions

restricts change, even within the class).

Q> What is static block


Ans :- Static block is used for initializing the static variables. This block gets
executed when the class is loaded in the memory. A class can have multiple
Static blocks, which will execute in the same sequence in which they have been
written into the program.
class JavaExample{
static int num;
static String mystr;
static
{
num = 97;
mystr = "Static keyword in Java";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}

SeleniumForSure 12 Bipin Thakare | 7798452716


Java Interview Questions

public static void main(String[] args) {

int max = 100;


System.out.println("Generate Prime numbers between 1 and " + max);

// loop through the numbers one by one


for (int i = 1; i<max; i++)
{
boolean isPrimeNumber = true;
// check to see if the number is prime
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrimeNumber = false;
break; // exit the inner for loop
}
}
// print the number if prime
if (isPrimeNumber) {
System.out.print(i + " ");
}
}

SeleniumForSure 1 Bipin Thakare | 7798452716


Java Interview Questions

public static void main(String[] args) {

int max = 100;

System.out.println("Generate Prime numbers between 1 and " + max);

// loop through the numbers one by one

for (int i = 1; i<max; i++) {

boolean isPrimeNumber = true;

// check to see if the number is prime

for (int j = 2; j < i; j++) {

if (i % j == 0) {

isPrimeNumber = false;

break; // exit the inner for loop

// print the number if prime

if (isPrimeNumber) {

System.out.print(i + " ");

SeleniumForSure 1 Bipin Thakare | 7798452716


Java Interview Questions

Java Program To Find Duplicate Elements In An Array

class DuplicatesInArray
{
public static void main(String[] args)
{
String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz"};

//1. Using Brute Force Method

for (int i = 0; i < strArray.length-1; i++)


{
for (int j = i+1; j < strArray.length; j++)
{
if( (strArray[i].equals(strArray[j])) && (i != j) )
{
System.out.println("Duplicate Element is : "+strArray[i]);
}
}
}

SeleniumForSure 1 Bipin Thakare | 7798452716


Java Interview Questions

program to find out duplicate characters in a String


public static void main(String[] args){
String s="Don't love me!";

s=s.toLowerCase();

char[] chAry=s.toCharArray();

int[] counter=new int[26];

for(char ch:chAry){
int idx=ch-'a';
if(idx<0 || idx>25){
continue;
}

counter[idx]++;
}

for(int i=0;i<counter.length;i++){

if(counter[i]>1){
char ch=(char)('a'+i);
System.out.printf("%c is duplicate,duplicate count=%d \r\n",
ch,counter[i]);
}
}
}

SeleniumForSure 1 Bipin Thakare | 7798452716


Selenium Interview Questions

Selenium Interview Question

Q>What are the advantages of automation testing? (Cybage, Abiba


system)
Ans:-
It supports execution of repeated test cases.
It facilitates parallel execution.
It aids in testing a large test matrix.
It improves accuracy because there are no chances of human errors.
It saves time and money.

Q> Can you please explain Selenium Architecture? (Infy, Cybage,


Emc^2)
Ans:-

Q> What type of test you have automated? (Wipro, techM, infinity)
Ans- Automation mainly focuses on regression testing,smoke testing
and some time you can for End to End test cases.

Q> How many test cases you have automated per day? (Intuit, sears,
Amazon)
Ans- It totally depends on your manual test cases. Sometimes we can
automate 3-4 test cases per day which contain limited operation and
some validation. Some test cases may take 1 day or more than one day
as well.
It totally depends on test case complexity.

Q> How to work with Chrome, IE or any other third party driver? Why
we need separate driver for them? (talentica, xpanxion,vertis,
JaMocha tech)

SeleniumForSure 1 Bipin Thakare | 7798452716


Selenium Interview Questions

Ans- Selenium by default supports only Firefox browser so in order to


work with Chrome and IE browser we need to download separate
drivers for them
and specify the path.

Q> what are the challenges involved with selenium ( MindTree,


Persistent, Nautica)
Ans:-

1. Generating useful test status reports


1. Dealing with pop-up windows
2. Testing Flash or Silverlight apps
3. Unexpected error launching Internet Explorer. Browser zoom level
should be set to 100% by default for the IE browser to overcome this
error
5. Capturing screen shots, either to file or in some form of report

Q> What are the challenges you have faced while automating your
application? (Kpit, 3 I infotech, Aftek, CMC limited, Nokia Siemens )
Ans:-

Q> What is Alert window/ JavaScript Alert and How to handle alert in
Selenium Webdriver? ( DataMatric, Eclerx)
Ans:- please refer to notes for same .

Q> Have you ever worked on frames? In addition, how to handle


frames in Selenium? (Fulcrum, cybage, geometric,vertis, NTT data)
Ans:- Please refer to notes for same.

SeleniumForSure 2 Bipin Thakare | 7798452716


Selenium Interview Questions

Q> What are different locators available in Selenium? (Real soft, CA


technologies, quest)
Ans:- ID, ClassName, LinkText, partialLinkText, xpath, css etc

Q> what are different xpath functions ( Target, amazon, cilisious,


capco, sunguard)
Ans:- contains(), starts-with(), text() etc

Q> How to verify checkbox (any element) is enable/disabled/


checked/Unchecked/ displayed/ not displayed? (Xpanxion,
symphony, vodafone, xoriant, igate)
Ans:-
isDisplayed();
isEnabled();
isSelected();
Example:- System.out.println(radios.get(0).getAttribute("checked"));
//is selected or not

Q> Difference between QUIT and Close? (Infy, tcs, L&T, IBM, Barclays )
Ans:-
driver.close – It closes the the browser window on which the focus is
set.
driver.quit – It basically calls driver.dispose method which in turn closes
all the browser windows and ends the WebDriver session gracefully.

Q> What is default Page Load Timeout in selenium? ( Mastek,


Nihilent)
Ans:- its zero. thats why we need to add waits in our program

SeleniumForSure 3 Bipin Thakare | 7798452716


Selenium Interview Questions

Q> What are different types of wait and difference between them?
Which one you have used frequently? (Collabra, Symantec, Balaji
solutions, JP morgan, amazon, )
Ans:- please refer to the notes.

Q> What is JavaScript Executor and where you have used JavaScript
executor? ( talentica, Sasken, GE, CGI)
Ans:-
JavaScriptExecutor is an interface which provides mechanism to
execute Javascript through selenium driver.
It provides executescript & "executeAsyncScript" methods, to run
JavaScript in the context of the currently selected frame or window.
Sometimes selenium click() does not work, we have used
JavaScriptExecutor to make click happen

Q> How to capture Screenshot in Selenium? (Rediff, Cynapse, IBM)


Ans:-
Below code captures the screenshot
public static void ScreenShot(WebDriver driver,String screenshotName)
throws IOException
{
TakesScreenshot ts =(TakesScreenshot)driver;
File Source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(Source, new
File("./ScreenShots/"+screenshotName+".png"));
}

Q> Can we capture screenshot only when test fails? (Nihilent, L&T,
KPIT, Nuance)
Ans:- yes. below code will do that

@AfterMethod

SeleniumForSure 4 Bipin Thakare | 7798452716


Selenium Interview Questions

public void tearDown(ITestResult result) throws IOException


//ITestResult is an interface which give information about our
current test case which is under execution
// result variable will store all the details of @Test along with the
pass or fail result
{
if(ITestResult.FAILURE==result.getStatus())
{
UtilityScrnSht.ScreenShot(Page.driver,
result.getName()); //user created method
}
}

Q> Difference between WebDriver listner and TestNG listner? Usage


of the same? (Nuance, 3I, Emc2)
Ans:- You must have always craved for more logs from the Webdriver
so that you can debug your scripts or may be log more information
about your tests.
Here is your answer to it, WebDriverEventListner and
TestNgListner(ITestListener Interface.)
In TestNg you can use Listeners in Annotation.
WebDriverEventListener – This is an interface, which have some
predefined methods so we will implement all of these methods.
Difference:- TestNG Listener are triggered at test level such as before
starting test after the test or when test fails etc;
whereas WebDriver Listener are triggered at component level such as
before click, after click etc

Q> How to scroll in Selenium Webdriver? (Persistent, TechM,


dataMatrix, capita)

SeleniumForSure 5 Bipin Thakare | 7798452716


Selenium Interview Questions

Ans:- there are two ways to do that


1>use Java Script
Example:- // This will scroll page 400 pixel vertical
((JavascriptExecutor)driver).executeScript("scroll(0,400)");

2> use robot class


Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);

Q> How to upload files in Selenium? Have you ever used AutoIT?
(Plivo, Accenture, Igate,capita)
Ans:- Refer notes for same

Q> Diffrence between findElement and FindElements? (Sonata,


cognizant,capita)
Ans:-
FindElement:- used in targetting single webelement. If targeted
element is not found on the page then it will throw
NoSuchElementException .
FindElements:- used in targetting multiple webelement. If not found
any element on current page as per given element locator mechanism,
it will return empty list.

Q> What is log4j And How to generate log files in Selenium? (Xorient)
Ans:-Log file is just simple file, which keep track of the record or event
or info when any event happens or any software run. This whole
process known as logging.
We can create log file as simple log file as well as HTML format.
Log4j is open source project from Apache which help us achive above
mentioned things.

SeleniumForSure 6 Bipin Thakare | 7798452716


Selenium Interview Questions

Q> Explain what is assertion in Selenium and what are the types of
assertion? (Nucleus, persistent, Infosys)
Ans:- Asserts helps us to verify the conditions of the test and decide
whether test has failed or passed. A test is considered successful ONLY
if it is completed without throwing any exception.
Assertions in selenium can be used in 3 modes which are explained
below:
1. assert: If you use assert in your tests then the test will be aborted if
the assert fails. Next test case will start executing in case you are
running a test suite.
2. verify: If verify is used then the test case will not abort even if the
verify fails. It will continue executing and log the failure for the failed
conditions.
3. waitFor: waitFor command waits for the condition to become true. If
the condition is true already the test case continues else it waits for the
conditions to become true. If the condition doesn t becomes true
within specified time-out period test will fail and halt.

Q> what is the difference between assert and verify in selenium (all
the companies )
Ans:- When an assert fails, the test will be aborted.
Where if a verify fails, the test will continue executing and logging the
failure.
So when Assertion fails all test steps after that line of code are skipped
:(To resolve this we write this command in try catch block :)

Q> Explain the difference between single and double slash in X-path?
(Magneto, Zenasr)
Ans:-
Single slash ( / ) start selection from the document node
It allows you to create absolute path expressions

Double slash ( // ) start selection matching anywhere in the document

SeleniumForSure 7 Bipin Thakare | 7798452716


Selenium Interview Questions

It enables to create relative path expressions

Q> How to type inside text box without using sendKeys() method
(Pubmatic, BMC, I gate)
Ans:- We need to use JavaScriptExecutor . Refer to Java Script notes for
details
example:-
// Open application
driver.get("enter your application URL");

// This will execute JavaScript in your script


((JavascriptExecutor)driver).executeScript("document.getElementById('
Enter id of input box here').value='Bipin' ");

Q> What is better xpath or .css?


Ans :- CSS selectors perform far better than Xpath and it is well
documented in Selenium community. Here are some reasons,
 Xpath engines are different in each browser, hence make them
inconsistent
 IE does not have a native xpath engine, therefore selenium injects
its own xpath engine for compatibility of its API. Hence we lose
the advantage of using native browser features that WebDriver
inherently promotes.
 Xpath tend to become complex and hence make hard to read .
However there are some situations where, you need to use xpath, for
example, searching for a parent element or searching element by its
text

Q> What is Webdriver? (synechron, Hitachi, Simens )


Ans :- Its an interface.

Q> How would you handle dynamic elements while automating?


(Infinite, Wipro, Kretio)

SeleniumForSure 8 Bipin Thakare | 7798452716


Selenium Interview Questions

Ans :- We can use Xpath methods such as starts-with or contains

Q> What are profiles in selenium? (Dautche bank, 3I infotech)


Ans :- This feature is available only with firefox.
If you want to open an instance of firefox which has your plugins &
bookmarks then one can use firefox profile .
FirefoxProfile profile = new FirefoxProfile(new File("D:\\Selenium
Profile"));
WebDriver driver = new FirefoxDriver(profile);

Q>Is there any other way to find xpath other than


firebug?(Synechron)
Ans :- One can right click on Webelement and choose inspect element
option.

Q> How would you automate charts/graphs/tool tips? (NTT data,JP


Morgan, Mphasis )
Ans:- Many web applications contains charts to show different data In
chart view. One of the chart they are using Is Pie chart. It Is very
Important for us to know how to automate these pie charts In
selenium WebDriver test. Few of the charts are very easy to automate
but It Is very hard to automate some charts as we are unable to locate
parts of pie chart.
@Test
public void pieChart(){
//Locate pie chart elements based on different colors.
WebElement VioleteColor =
driver.findElement(By.xpath("//*[contains(@class,'yui3-
svgSvgPieSlice')][@fill='#66007f']"));
WebElement GreenColor =
driver.findElement(By.xpath("//*[contains(@class,'yui3-
svgSvgPieSlice')][@fill='#295454']"));

SeleniumForSure 9 Bipin Thakare | 7798452716


Selenium Interview Questions

WebElement GreyColor =
driver.findElement(By.xpath("//*[contains(@class,'yui3-
svgSvgPieSlice')][@fill='#e8cdb7']"));
WebElement LightVioleteColor =
driver.findElement(By.xpath("//*[contains(@class,'yui3-
svgSvgPieSlice')][@fill='#996ab2']"));
WebElement BrownColor =
driver.findElement(By.xpath("//*[contains(@class,'yui3-
svgSvgPieSlice')][@fill='#a86f41']"));

//locate tooltip pie chart.


WebElement ToolTip =
driver.findElement(By.xpath("//div[contains(@id,'_tooltip')]"));

//Click on pie chart parts and get tooltip values.


System.out.println("-X-X-X-X-X-X-X-X- Violete Part -X-X-X-X-X-X-X-X-");
VioleteColor.click();
System.out.println(ToolTip.getText());
System.out.println();

System.out.println("-X-X-X-X-X-X-X-X- Grey Part -X-X-X-X-X-X-X-X-");


GreyColor.click();
System.out.println(ToolTip.getText());
System.out.println();

System.out.println("-X-X-X-X-X-X-X-X- Light Violete Part -X-X-X-X-X-X-X-


X-");
LightVioleteColor.click();
System.out.println(ToolTip.getText());
System.out.println();

System.out.println("-X-X-X-X-X-X-X-X- Green Part -X-X-X-X-X-X-X-X-");


GreenColor.click();

SeleniumForSure 10 Bipin Thakare | 7798452716


Selenium Interview Questions

System.out.println(ToolTip.getText());
System.out.println();

System.out.println("-X-X-X-X-X-X-X-X- Brown Part -X-X-X-X-X-X-X-X-");


BrownColor.click();
System.out.println(ToolTip.getText());
}
}

Q> What is the tag used for links? (unknown)


Ans :- <a>

Q>How to scroll the webpage using webdriver? (Sunguard, Vodafone,


HSBC, Synechron, PGS, Fujitsu)
Ans :- Selenium handle scrolling page automatically but if want to scroll
page using Selenium then yes we can do easily using JavaScript.

We have method scroll(horizontal, vertical) i.e. scroll(0,400)


To execute JavaScript code inside Selenium script we can take the help
of JavascriptExecutor

JavascriptExecutor is an Interface which is available in


package org.openqa.selenium.JavascriptExecutor;
Inside this Interface we have a method called executeScript()- so
whatever script you will pass as a string It will be executed by
JavascriptExecutor.

public class ScrollTestCase {

SeleniumForSure 11 Bipin Thakare | 7798452716


Selenium Interview Questions

public static void main(String[] args) throws Exception {

// load browser
WebDriver driver=new FirefoxDriver();

// maximize browser
driver.manage().window().maximize();

// Open Application
driver.get("http://jqueryui.com");

// Wait for 5 second


Thread.sleep(5000);

// This will scroll page 400 pixel vertical


((JavascriptExecutor)driver).executeScript("scroll(0,400)");

There is one more way to do the same .


If you want to use the keys form the keyboard to scroll UP or
DOWN you can use the WebDriver sendKeys() method and pass
the PAGE_UP or PAGE_DOWN as an argument:
@Test(groups = {"smoke"})
public void test_Scroll_Page_Using_Keys() throws Exception {
init();

SeleniumForSure 12 Bipin Thakare | 7798452716


Selenium Interview Questions

driver.navigate().to("http://www.alexa.com/topsites/countries;15/L
U");

Actions action = new Actions(driver);


action.sendKeys(Keys.PAGE_DOWN);
waitSeconds(2);
action.click(driver.findElement(By.partialLinkText("Google.com.ph")))
.perform();
}

Q>How to find the present URL on the application? (Persistent,


accenture)
Ans :- WebDriver driver = new WebDriver();
String url = driver.getCurrentUrl();

Q>How to find the number of browsers opened by selenium?


Ans :- driver.getWindowHandles()

Q> how to use open new tab in existing browser (One network, media
ocean, PTC)
Ans :-

driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL,"t");
or
driver.navigate().to(urlToOpen);

Actions action = new Actions(driver);


// close the newly opened tab
action.keyDown(Keys.CONTROL).sendKeys("w").perform();
// switch back to original
action.keyDown(Keys.CONTROL).sendKeys("1").perform();
Ctrl+t combination to open a new tab, Ctrl+w to close it, and to switch
back to original tab I used Ctrl+1 (the first tab).

SeleniumForSure 13 Bipin Thakare | 7798452716


Selenium Interview Questions

Q>How will you simulate a keyboard action using webdriver?


Ans :- Please refer to notes

Q>Write a sample code to perform browser refresh(Amazon,


prospance, quest, Dautche bank)
Ans :- there are multiple ways to do it
1.driver.navigate().refresh();
2.driver.get(driver.getCurrentUrl());
3.driver.navigate().to(driver.getCurrentUrl());
4.driver.findElement(By.id("Contact-us")).sendKeys(Keys.F5);
5.driver.executeScript("history.go(0)");

Q>Difference between click and clickandwait statements? (Sapient )


Ans :- click command only execute the command and then proceed to
next command of the script.
"clickAndWait" command is some different than "click" command. It
will wait for page to load means next command will be not executed
until page not loaded successfully. You need to use this command when
your
are clicking somewhere on page of software web application and page
start reloading content.

Q>How to run the selenium webdriver scripts in the background? Write


a sample code to perform that action. (Accenture, CGI, Lloyds)
Ans :- To achieve this one has to use either HtmlUnitDriver or
PhantomJS

Q>I have a hidden webelement in a page and like to get the static text.
How to do that? (Eclarx, Accenture)

SeleniumForSure 14 Bipin Thakare | 7798452716


Selenium Interview Questions

Ans :-
Since a user cannot read text in a hidden element, WebDriver will not
allow access to it as well. However, it is possible to use Javascript
execution abilities to call getText directly from the element..."
public static String getText(WebDriver driver, WebElement element){
return (String) ((JavascriptExecutor) driver).executeScript(
"return jQuery(arguments[0]).text();", element);
}

Q>How do I know when a page has finished loading? (one network )


Ans :- Selenium does this by default for us.

Q>How do you handle secured connection error in HTTPS ? (Sunguard,


Infosys, Cybage)
Ans :-
For Firefox :-
//Creating new Firefox profile
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
driver = new FirefoxDriver(profile);

For Chrome :-
DesiredCapabilities handlSSLErr = DesiredCapabilities.chrome ()
handlSSLErr.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true)
WebDriver driver = new ChromeDriver (handlSSLErr);

Q>Does WebDriver support file uploads? (unknown)


Ans :- No

SeleniumForSure 15 Bipin Thakare | 7798452716


Selenium Interview Questions

Q>I got an unexpected pop up/alert error in my screen, how will you
handle in your script? (Unknown)
Ans :- refer popup and alert notes for same

Q> How to highlight webElement in Selenium? (Synechron,


A4SureTech, Sasken)
For example :-

Ans :-
driver.get("http://www.facebook.com");

// Create the JavascriptExecutor object


JavascriptExecutor js=(JavascriptExecutor)driver;

// find element using id attribute


WebElement username= driver.findElement(By.id("email"));

// call the executeScript method


js.executeScript("arguments[0].setAttribute('style,'border: solid 2px
red'');", username);

Q> how to find out xpath or view dom when test case is already
running (Barclays, Amdocs, cognizant)
Ans :- You will have to create firefoxprofile and add the firebug and
firepath plugins into that.

SeleniumForSure 16 Bipin Thakare | 7798452716


Java Interview Questions

Q> How can I swap two variables without using a third variable?
=====================================================
( Asked in Xoriant, media ocean, TCS, tech M )

Add two variables and assign the value into First variable. Subtract the Second value with the result
Value and assign to Second variable.
Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable.
Example:

int a=5,b=10;

a=a+b;

b=a-b;

a=a-b;

You can also use an XOR swap.


for example:

int a = 5; int b = 10;


a = a ^ b;

b = a ^ b;

a = a ^ b;

SeleniumForSure 1 Bipin Thakare | 7798452716


Selenium Interview Questions

TestNG Interview Question

Q) What is TestNG? (symphony telca)


Ans:- TestNG is an automated open source testing framework.

Q) Why you have used TestNG in your framework? Can you compare
JUNIT with TestNG framework? (Wipro,Cybage, Avaya, Teito)
Ans:-
Compare to JUnit annotations, TestNG are easy to understand
Unlike JUnit, TestNG does not require to declare @BeforeClass and
@AfterClass
Method name constraint is not there in TestNG
TestNG allows you the grouping of test cases easily which is not
possible in JUnit
TestNG supports following three additional setup: @Before/AfterSuite,
@Before/AfterTest and @Before/AfterGroup
TestNG does not need to extend any class
In TestNG, it is possible to run selenium test cases in parallel
Based on group TestNG allows you to execute the test cases
TestNG allows you to determine the dependent test cases; each test
case is autonomous to other test case

Q) What are different annotation present in TestNG? Can you name


few amongst them ?(KPIT, Techm, Citi bank, TCS)
Ans:-
@BeforeSuite
@AfterSuite
@BeforeTest
@AfterTest
@BeforeGroups
@AfterGroups
@BeforeClass

SeleniumForSure 1 Bipin Thakare | 7798452716


Selenium Interview Questions

@AfterClass
@BeforeMethod
@AfterMethod

Q) What is priority feature in TestNG? In addition, how we can use


this? (Synechron,Kpit, capgemeni, fluent India)
Ans:- If you want the @Test methods to be executed in your order,
then you need to use the ‘priority‘ .
Like First we need to execute a test case "Registration" before login. In
order to achive, we use need to add annotation as @Test(priority=??).
Sequence of execution is in ascending order of value. 0 is having
highest priority so it will be executed first. There is no need for your
values to be consecutive
Example:- @Test (priority=0)
Q) What is dependsOnMethods (Zensar, Wipro )
Ans:-
In real time, you will come across many situations where you have to
create test cases which are dependent on the previous test case.
Take an example I have 3 test cases.
First one which verify login credential and start application, second test
case check some validation or do some activity, third test case simply
just for log-out activity.
If my first test case does not work (failed) then it does not make any
sense to run second and third test case. So in these types of scenarios
you can use dependency between test cases.
Syntax- @Test( dependsOnMethods = {"loginTestCase"} )

SeleniumForSure 2 Bipin Thakare | 7798452716


Selenium Interview Questions

Q) What is testng.xml file in TestNG? (media ocean, HSBC, NTT data)


Ans:-
In any project, you will end up to a place where you need to execute so
many test cases on a run. Running a set of test cases together is call
executing a Test Suite.
Those test cases can be dependent to each other or may have to be
executed in a certain order. testng.xml file where you will configure
your test run, set test dependency, include or exclude any test,
method, class or package and set priority etc.

Q) How to group test cases in TestNG?


Ans:-
In TestNg you can form a group of test cases and run it .It allows us to
execute only set of groups while excluding another set.
Groups are specified in testng.xml file and can be used with tag.
Example:-
public class groupExamples {
@Test(groups="Regression")
public void testCaseOne()
{
System.out.println("Im in testCaseOne - And in Regression
Group");
}
@Test(groups="Regression")
public void testCaseTwo(){
System.out.println("Im in testCaseTwo - And in Regression
Group");
}
@Test(groups="Smoke Test")
public void testCaseThree(){
System.out.println("Im in testCaseThree - And in Smoke Test
Group");

SeleniumForSure 3 Bipin Thakare | 7798452716


Selenium Interview Questions

}
@Test(groups="Regression")
public void testCaseFour(){
System.out.println("Im in testCaseFour - And in Regression
Group");
}
}

The below is the XML file to execute, the test methods with group.
We will execute the group Regression which will execute the test
methods which are defined with group as Regression

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


<suite name="Sample Suite">
<test name="testing">
<groups>
<run>
<include name="Regression"/>
</run>
</groups>
<classes>
<class name="com.example.group.groupExamples" />
</classes>
</test>
</suite>

Q) How to execute multiple test cases in Selenium? (Amdocs


,Accenture)
Ans:- using TestNG.xml

Q) How to execute parallel test cases in Selenium? (PTC, mindtree)


Ans:- There are two ways

SeleniumForSure 4 Bipin Thakare | 7798452716


Selenium Interview Questions

1> using DataProvider anotation :- @DataProvider(parallel=true)


2> using testng.xml :- <suite name="My suite" parallel="methods" >
Q) What is Data provider in TestNG?
Ans:- It is used to parameterize the test. we can also achive parallel
execution using same.

Q) How to skip or disable particular test case? (Infy, persistent,


Avaya, Wipro)
Ans:- Two ways to do it.
1>@Test(enabled=false)
2>Write throw new SkipException("any message"); inside a Test
method which you want to skip.

Q) How to execute only failed test cases in Selenium? (Synerzip, HCL,


Accenture, Capgemeni)
Ans:-
Every time tests fail in a suite, TestNG creates a file called testng-
failed.xml in the output directory.
This XML file contains the necessary information to rerun only these
methods that failed, utlizing this we can easily rerun the failed tests
without having to run the entire test suite.

SeleniumForSure 5 Bipin Thakare | 7798452716

You might also like