0% found this document useful (0 votes)
30 views

Core Java Interview Questions and Answers by Advanto

Interview questions for Java and Selenium

Uploaded by

Sandip Pathak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Core Java Interview Questions and Answers by Advanto

Interview questions for Java and Selenium

Uploaded by

Sandip Pathak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Q #1) What is JAVA?

Answer: Java is a high-level programming language and is platform-independent.


Java is a collection of objects. It was developed by Sun Microsystems. There are a lot of applications, websites, and games that are
developed using Java.

Q #2) What are the features of JAVA?


Answer: Features of Java are as follows:
 OOP concepts
 Object-oriented
 Inheritance
 Encapsulation
 Polymorphism
 Abstraction
 Platform independent: A single program works on different platforms without any modification.
 High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT converts the bytecode into machine
language and then JVM starts the execution.
 Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which is called the main thread. The user can
create multiple threads by extending the thread class or by implementing the Runnable interface.
Q #3) How does Java enable high performance?
Answer: Java uses Just In Time compiler to enable high performance. It is used to convert the instructions into bytecodes.
Q #4) Name the Java IDE’s?
Answer: Eclipse and NetBeans are the IDE’s of JAVA.
Q #5) What do you mean by Constructor?
Answer: Constructor can be explained in detail with enlisted points:
 When a new object is created in a program a constructor gets invoked corresponding to the class.
 The constructor is a method which has the same name as the class name.
 If a user doesn’t create a constructor implicitly a default constructor will be created.
 The constructor can be overloaded.
 If the user created a constructor with a parameter then he should create another constructor explicitly without a parameter.
Q #6) What is meant by the Local variable and the Instance variable?
Answer:
Local variables are defined in the method and scope of the variables that exist inside the method itself.
Instance variable is defined inside the class and outside the method and the scope of the variables exists throughout the class.
Q #7) What is a Class?
Answer: All Java codes are defined in a Class. It has variables and methods.
Variables are attributes which define the state of a class.
Methods are the place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy the
particular requirement.
Example:
public class Addition{ //Class name declaration
int a = 5; //Variable declaration
int b= 5;
public void add(){ //Method declaration
int c = a+b;
}
}
Q #8) What is an Object?
Answer: An instance of a class is called an object. The object has state and behaviour.
Whenever the JVM reads the “new()” keyword then it will create an instance of that class.

Example:
public class Addition{
public static void main(String[] args){
Addion add = new Addition();//Object creation
}
}
The above code creates the object for the Addition class.

Q #9)What are the OOPs concepts?


Answer: OOPs concepts include:
 Inheritance
 Encapsulation
 Polymorphism
 Abstraction
 Interface
Suggested Read =>> Top OOPs Interview Questions
Q #10) What is Inheritance?
Answer: Inheritance means one class can extend to another class. So that the codes can be reused from one class to another
class. The existing class is known as the Super class whereas the derived class is known as a sub class.
Example:
Super class:
public class Manupulation(){
}
Sub class:
public class Addition extends Manipulation(){
}
Inheritance is only applicable to the public and protected members only. Private members can’t be inherited.

Q #11) What is Encapsulation?


Answer: Purpose of Encapsulation:
It refers to the bundling of data (attributes or properties) and methods (functions or behaviors) that operate on the data into a single unit,
called a class. Encapsulation hides the internal state of an object from the outside world and restricts access to it through well-defined
interfaces.
 Protects the code from others.
 Code maintainability.
Example:
We are declaring ‘a’ as an integer variable and it should not be negative.

public class Addition(){


int a=5;
}
If someone changes the exact variable as “a = -5” then it is bad.
In order to overcome the problem we need to follow the steps below:
 We can make the variable private or protected.
 Use public accessor methods such as set<property> and get<property>.
So that the above code can be modified as:
public class Addition(){
private int a = 5; //Here the variable is marked as private
}
The code below shows the getter and setter.
Conditions can be provided while setting the variable.

get A(){
}
set A(int a){
if(a&gt;0){// Here condition is applied
.........
}
}
For encapsulation, we need to make all the instance variables private and create setter and getter for those variables. Which in turn will
force others to call the setters rather than access the data directly.

Q #12) What is Polymorphism?


Answer: Polymorphism means many forms.
A single object can refer to the super-class or sub-class depending on the reference type which is called polymorphism.

It allows objects of different classes to be treated as objects of a common superclass. It enables a single interface (method or function) to
represent multiple forms or behaviours based on the object's type or class hierarchy. polymorphism enables methods to behave
differently based on the object they are called on, leading to flexibility and extensibility in code design.
Using the Manipulation reference type we can call the Addition class “add()” method. This ability is known as Polymorphism.
Polymorphism is applicable for overriding and not for overloading.

Q #13) What is meant by Method Overriding?


Answer: Method overriding happens if the sub-class method satisfies the below conditions with the Super-class method:
 Method name should be the same
 The argument should be the same
 Return type should also be the same
The key benefit of overriding is that the Sub-class can provide some specific information about that sub-class type than the super-class.

Example:
public class Manipulation{ //Super class
public void add(){
………………
}
}

Public class Addition extends Manipulation(){


Public void add(){
………..
}
Public static void main(String args[]){
Manipulation addition = new Addition(); //Polimorphism is applied
addition.add(); // It calls the Sub class add() method
}
}
addition.add() method calls the add() method in the Sub-class and not the parent class. So it overrides the Super-class method and is
known as Method Overriding.
Q #14) What is meant by Overloading?
Answer: Method overloading happens for different classes or within the same class.
For method overloading, sub-class method should satisfy the below conditions with the Super-class method (or) methods in
the same class itself:
 Same method name
 Different argument types
 There may be different return types
Example:
public class Manipulation{ //Super class
public void add(String name){ //String parameter
………………
}
}

Public class Addition extends Manipulation(){


Public void add(){//No Parameter
………..
}
Public void add(int a){ //integer parameter

}
Public static void main(String args[]){
Addition addition = new Addition();
addition.add();
}
}
Here the add() method has different parameters in the Addition class is overloaded in the same class as with the super-class.

Note: Polymorphism is not applicable for method overloading.


Q #15) What is meant by Interface?
Answer: An interface is a template which has only method declarations and not the method implementation.
Multiple inheritances cannot be achieved in java. To overcome this problem the Interface concept is introduced.
 All the methods in the interface are internally public abstract void.
 All the variables in the interface are internally public static final that is constants.
 Classes can implement the interface and not extends.
 The class which implements the interface should provide an implementation for all the methods declared in the interface.
Q #16) What is meant by Abstract class?
Answer: We can create the Abstract class by using the “Abstract” keyword before the class name. An abstract class can have both
“Abstract” methods and “Non-abstract” methods that are a concrete class.
Abstract method:
The method which has only the declaration and not the implementation is called the abstract method and it has the keyword called
“abstract”. Declarations ends with a semicolon.

 An abstract class may have a non- abstract method also.


 The concrete Subclass which extends the Abstract class should provide the implementation for abstract methods.

Q #17) Difference between Array and Array List.


Answer: The Difference between Array and Array List can be understood from the table below:
Array Array List

Size should be given at the time of array declaration. Size may not be required. It changes the size dynamically.

String[] name = new String[2] ArrayList name = new ArrayList

To put an object into array we need to specify the No index required.


index.
name.add(“book”)
name[1] = “book”

Array is not type parameterized ArrayList in java 5.0 are parameterized.

Eg: This angle bracket is a type parameter which means a list


of String.
Q #18) Difference between String, String Builder, and String Buffer.
Answer:

`String`, `StringBuilder`, and `StringBuffer` are all classes used to manipulate strings in Java, but they have different characteristics and
are suited for different use cases. Here's a comparison of the three:

1. String:
- `String` objects in Java are immutable, meaning their values cannot be changed once they are created.
- Any operation that appears to modify a `String`, such as concatenation or substring, actually creates a new `String` object.
- Since `String` objects are immutable, they are thread-safe, making them suitable for use in multithreaded environments.
- Immutable objects are also more predictable and can be optimized by the Java Virtual Machine (JVM).

2. StringBuilder:
- `StringBuilder` is a mutable sequence of characters that can be modified without creating new objects.
- It is more efficient than `String` for concatenating multiple strings or performing frequent string manipulations, as it avoids the
overhead of creating new objects.
- `StringBuilder` is not thread-safe, meaning it is not safe to use concurrently by multiple threads without external synchronization.
- It is commonly used in scenarios where mutable string operations are needed, such as building dynamic strings in loops or
constructing large strings.

3. StringBuffer:
- `StringBuffer` is similar to `StringBuilder` in that it represents a mutable sequence of characters.
- However, `StringBuffer` is thread-safe, as its methods are synchronized, making it safe to use concurrently by multiple threads without
external synchronization.
- Due to the synchronization overhead, `StringBuffer` may be slower than `StringBuilder` for single-threaded applications or scenarios
where thread safety is not required.
- `StringBuffer` is less commonly used in modern Java development compared to `StringBuilder`, except in cases where thread safety
is a concern.
In summary, `String` is immutable and thread-safe, `StringBuilder` is mutable but not thread-safe, and `StringBuffer` is mutable and
thread-safe. Developers should choose the appropriate class based on the specific requirements of their application, considering factors
such as performance, thread safety, and mutability.

Q #19) Explain about Public and Private access specifiers.


Answer: Methods and instance variables are known as members.
Public:
Public members are visible in the same package as well as the outside package that is for other packages. Public members of Class A
are visible to Class B (same package) as well as Class C (different packages).

Private:
Private members are visible in the same class only and not for the other classes in the same package as well as classes in the outside
packages. Private members in class A are visible only in that class. It is invisible for class B as well as class C.

Q #20) Difference between Default and Protected access specifiers.


Answer:
Default: Methods and variables declared in a class without any access specifiers are called default.
Default members in Class A are visible to the other classes which are inside the package and invisible to the classes which are outside
the package.

Protected:
Protected is the same as Default but if a class extends then it is visible even if it is outside the package.

Class A members are visible to Class B because it is inside the package. For Class C it is invisible but if Class C extends Class A then
the members are visible to Class C even if it is outside the package.

Q #21) Difference between HashMap and HashTable.


Answer: The difference between HashMap and HashTable can be seen below:
HashMap HashTable

Methods are not synchronized Key methods are synchronized

Not thread safety Thread safety

Iterator is used to iterate the values Enumerator is used to iterate the values

Allows one null key and multiple null values Doesn’t allow anything that is null

Performance is high than HashTable Performance is slow


Q #22) Difference between HashSet and TreeSet.
Answer: The difference between HashSet and TreeSet can be seen below:
HashSet TreeSet

Inserted elements are in random order Maintains the elements in the sorted order

Can able to store null objects Couldn’t store null objects

Performance is fast Performance is slow

Q #23) Difference between Abstract class and Interface.


Answer: The differences between Abstract Class and Interface are as follows:
Abstract Class:
 Abstract classes have a default constructor and it is called whenever the concrete subclass is instantiated.
 It contains Abstract methods as well as Non-Abstract methods.
 The class which extends the Abstract class shouldn’t require the implementation of all the methods, only Abstract methods need
to be implemented in the concrete sub-class.
 Abstract class contains instance variables.
Interface:
 It doesn’t have any constructor and couldn’t be instantiated.
 The abstract method alone should be declared.
 Classes that implement the interface should provide the implementation for all the methods.
 The interface contains only constants.

Q #24) What is the meaning of Collections in Java?


Answer: A group of objects is known as collections. Collection is a framework that is designed to store the objects and manipulate the
design to store the objects.
Collections are used to perform the following operations:
 Searching
 Sorting
 Manipulation
 Insertion
 Deletion
A group of objects is known as collections. All the classes and interfaces for collecting are available in Java util package.
Q #25) What are all the Classes and Interfaces that are available in the collections?
Answer: Given below are the Classes and Interfaces that are available in Collections:
Interfaces:
 Collection
 List
 Set
 Map
 Sorted Set
 Sorted Map
 Queue
Classes:
 Lists:
 Array List
 Vector
 Linked List
Sets:
 Hash set
 Linked Hash Set
 Tree Set
Maps:
 Hash Map
 Hash Table
 TreeMap
 Linked Hashed Map
Queue:
 Priority Queue
Q #26) What is meant by Ordered and Sorted in collections?
Answer:
Ordered: It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the
values from the collection in a specific order.
Sorted: Sorting mechanisms can be applied internally or externally so that the group of objects sorted in a particular collection is based
on the properties of the objects.

Q #27) Explain the different lists available in the collection.


Answer: Values added to the list are based on the index position and it is ordered by index position. Duplicates are allowed.
The types of Lists are:
a) Array List:
 Fast iteration and fast Random Access.
 It is an ordered collection (by index) and not sorted.
 It implements the Random Access Interface.
 Array List maintains the insertion order and it accepts the duplicates. But it’s not sorted.
Example:
public class Fruits{
public static void main (String [ ] args){
ArrayList &lt;String&gt;names=new ArrayList &lt;String&gt;();
names.add (“apple”);
names.add (“cherry”);
names.add (“kiwi”);
names.add (“banana”);
names.add (“cherry”);
System.out.println (names);
}
}
Output:
[Apple, cherry, kiwi, banana, cherry]

b) Vector:
It is the same as Array List.

 Vector methods are synchronized.


 Thread safety.
 It also implements Random Access.
 Thread safety usually causes a performance hit.
 Vector also maintains the insertion order and accepts the duplicates.

Example:
public class Fruit {
public static void main (String [ ] args){
Vector &lt;String&gt; names = new Vector &lt;String&gt; ( );
names.add (“cherry”);
names.add (“apple”);
names.add (“banana”);
names.add (“kiwi”);
names.add (“apple”);
System.out.println (“names”);
}
}
Output:
[cherry,apple,banana,kiwi,apple]

c) Linked List:
 Elements are doubly linked to one another.
 Performance is slower than the Array list.
 Good choice for insertion and deletion.
 Maintains the insertion order and accepts the duplicates.
 In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.
Example:
public class Fruit {
public static void main (String [ ] args){
Linkedlist &lt;String&gt; names = new linkedlist &lt;String&gt; ( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}
Output:
[ banana,cherry,apple,kiwi,banana]

Q #28) Explain about Set and their types in a collection.


Answer: Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects
are identical or not. ('==' operator is used for reference comparison, while the equals() method is used for content comparison.)
a) Hash Set:
 Unordered and unsorted.
 Uses the hash code of the object to insert the values.
 It doesn’t follow any insertion order. Duplicates are not allowed.

Example:
public class Fruit {
public static void main (String[ ] args){
HashSet&lt;String&gt; names = new HashSet &lt;=String&gt;( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}
Output:
[banana, cherry, kiwi, apple]

b) Linked Hash set:


 An ordered version of the hash set is known as Linked Hash Set.
 Maintains a doubly-Linked list of all the elements.
 Use this when an iteration order is required.
 It maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.

Example:
public class Fruit {
public static void main (String[ ] args){
LinkedHashSet&lt;String&gt;; names = new LinkedHashSet &lt;String&gt;( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}
Output:
[banana, cherry, apple, kiwi]

c) Tree Set:
 It is one of the two sorted collections.
 Uses the “Read-Black” tree structure and guarantees that the elements will be in ascending order.
 We can construct a tree set with the constructor by using a comparable (or) comparator.
 TreeSet sorts the elements in ascending order. And duplicates are not allowed.

Example:
public class Fruits{
public static void main (String[ ]args) {
Treeset&lt;String&gt; names= new TreeSet&lt;String&gt;( ) ;
names.add(“cherry”);
names.add(“banana”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“cherry”);
System.out.println(names);
}
}
Output:
[apple, banana, cherry, kiwi]

Q #29) Explain about Map and its types.


Answer: Map cares about the unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a
value, based on the key. Like the set, the map also uses the “equals ( )” method to determine whether two keys are the same or different.
Map is of following types:
a) Hash Map:
 Unordered and unsorted map.
 Hashmap is a good choice when we don’t care about the order.
 It allows one null key and multiple null values.
 Duplicate keys are not allowed in Map.
 It doesn’t maintain any insertion order and is unsorted.

Example:
Public class Fruit{
Public static void main(String[ ] args){
HashMap&lt;Sting,String&gt; names =new HashMap&lt;String,String&gt;( );
names.put(“key1”,“cherry”);
names.put (“key2”,“banana”);
names.put (“key3”,“apple”);
names.put (“key4”,“kiwi”);
names.put (“key1”,“cherry”);
System.out.println(names);
}
}
Output:
{key2 =banana, key1=cherry, key4 =kiwi, key3= apple}

b) Hash Table:
 Like the vector key, methods of the class are synchronized.
 Thread safety and therefore slows the performance.
 It doesn’t allow anything that is null.
 Duplicate keys are not allowed.

Example:
public class Fruit{
public static void main(String[ ]args){
Hashtable&lt;Sting,String&gt; names =new Hashtable&lt;String,String&gt;( );
names.put(“key1”,“cherry”);
names.put(“key2”,“apple”);
names.put(“key3”,“banana”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
}
}
Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}

c) Linked Hash Map:


 Maintains insertion order.
 Slower than Hash map.
 I can expect a faster iteration.
 Duplicate keys are not allowed.

Example:
public class Fruit{
public static void main(String[ ] args){
LinkedHashMap&lt;Sting,String&gt; names =new LinkedHashMap&lt;String,String&gt;( );
names.put(“key1”,“cherry”);
names.put(“key2”,“apple”);
names.put(“key3”,“banana”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
}
}
Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}

d) TreeMap:
 Sorted Map.
 Like Tree set, we can construct a sort order with the constructor.
 It is sorted in ascending order based on the key. Duplicate keys are not allowed.

Example:
public class Fruit{
public static void main(String[ ]args){
TreeMap&lt;Sting,String&gt; names =new TreeMap&lt;String,String&gt;( );
names.put(“key1”,“cherry”);
names.put(“key2”,“banana”);
names.put(“key3”,“apple”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
}
}
Output:
{key1=cherry, key2=banana, key3 =apple, key4=kiwi}

Q #30) Explain the Priority Queue.


Answer: Queue Interface
Priority Queue: Linked list class has been enhanced to implement the queue interface. Queues can be handled with a linked list. The
purpose of a queue is “Priority-in, Priority-out”.
Hence elements are ordered either naturally or according to the comparator. The elements ordering represents their relative priority.

Q #31) What is meant by Exception?


Answer: An Exception is a problem that can occur during the normal flow of execution. A method can throw an exception when
something wails at runtime. If that exception couldn’t be handled, then the execution gets terminated before it completes the task.
If we handled the exception, then the normal flow gets continued. Exceptions are a subclass of java.lang.Exception.

Example for handling Exception:


try{
//Risky codes are surrounded by this block
}catch(Exception e){
//Exceptions are caught in catch block
}
Q #32) What are the types of Exceptions?
Answer: There are two types of Exceptions. They are explained below in detail.
a) Checked Exception:
These exceptions are checked by the compiler at the time of compilation. Classes that extend Throwable class except Runtime exception
and Error are called checked Exception.

Checked Exceptions must either declare the exception using throws keyword (or) surrounded by appropriate try/catch.

For Example, ClassNotFound Exception


b) Unchecked Exception:
These exceptions are not checked during the compile time by the compiler. The compiler doesn’t force to handle these exceptions. It
includes:
 Arithmetic Exception
 ArrayIndexOutOfBounds Exception
Q #33) What are the different ways to handle exceptions?
Answer: Two different ways to handle exceptions are explained below:
a) Using try/catch:
The risky code is surrounded by try block. If an exception occurs, then it is caught by the catch block which is followed by the try block.

Example:
class Manipulation{
public static void main(String[] args){
add();
}
Public void add(){
try{
addition();
}catch(Exception e){
e.printStacktrace();
}
}
}
b) By declaring throws keyword:
At the end of the method, we can declare the exception using throws keyword.

Example:
class Manipulation{
public static void main(String[] args){
add();
}
public void add() throws Exception{
addition();
}
}
Q #34) What are the advantages of Exception handling?
Answer: The advantages are as follows:
 The normal flow of the execution won’t be terminated if an exception gets handled
 We can identify the problem by using catch declaration

Q #35) What are the Exception handling keywords in Java?


Answer: Enlisted below are the two Exception Handling Keywords:
a) try:
When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed
either by catch (or) finally (or) both. But any one of the blocks is mandatory.

b) catch:
This is followed by a try block. Exceptions are caught here.

c) finally:
This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are
provided here.

Q #36) Explain about Exception Propagation.


Answer: Exception is first thrown from the method which is at the top of the stack. If it doesn’t catch, then it pops up the method and
moves to the previous method and so on until they are got.
This is called Exception propagation.

Example:
public class Manipulation{
public static void main(String[] args){
add();
}
public void add(){
addition();
}
From the above example, the stack looks like as shown below:

If an exception occurs in the addition() method is not caught, then it moves to the method add(). Then it is moved to the main() method
and then it will stop the flow of execution. It is called Exception Propagation.
Q #37) What is the final keyword in Java?
Answer:
Final variable: Once a variable is declared as final, then the value of the variable could not be changed. It is like a constant.
Example:
final int = 12;

Final method: A final keyword in a method, couldn’t be overridden. If a method is marked as a final, then it can’t be overridden by the
subclass.
Final class: If a class is declared as final, then the class couldn’t be subclassed. No class can extend the final class.
Q #38) What is a Thread?
Answer: In Java, the flow of execution is called Thread. Every java program has at least one thread called the main thread, the main
thread is created by JVM. The user can define their own threads by extending the Thread class (or) by implementing the Runnable
interface. Threads are executed concurrently.
Example:
public static void main(String[] args){//main thread starts here
}
Q #39) How do you make a thread in Java?
Answer: There are two ways available to make a thread.
a) Extend Thread class: Extending a Thread class and override the run method. The thread is available in java.lang.thread.
Example:
Public class Addition extends Thread {
public void run () {
}
}
The disadvantage of using a thread class is that we cannot extend any other classes because we have already extended the thread
class. We can overload the run () method in our class.

b) Implement Runnable interface: Another way is by implementing the runnable interface. For that, we should provide the
implementation for the run () method which is defined in the interface.
Example:
Public class Addition implements Runnable {
public void run () {
}
}
Q #40) Explain about join () method.
Answer: Join () method is used to join one thread with the end of the currently running thread.
Example:
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
t.join ();
}

Based on the above code, the main thread has started the execution. When it reaches the code t.start() then ‘thread t’ starts the own
stack for the execution. JVM switches between the main thread and ‘thread t’.
Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task, then only the main thread starts the execution.
It is a non-static method. The Join () method has an overloaded version. So we can mention the time duration in join () method also “.s”.

Q #41) What does the yield method of the Thread class do?
Answer: A yield () method moves the currently running thread to a runnable state and allows the other threads for execution. So that
equal priority threads have a chance to run. It is a static method. It doesn’t release any lock.
Yield () method moves the thread back to the Runnable state only, and not the thread to sleep (), wait () (or) block.
Example:
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
Thread.yield();
}
}
Q #42) Explain about wait () method.
Answer: wait () method is used to make the thread to wait in the waiting pool. When the wait () method is executed during a thread
execution then immediately the thread gives up the lock on the object and goes to the waiting pool. Wait () method tells the thread to wait
for a given amount of time.
Then the thread will wake up after notify () (or) notify all () method is called.

Wait() and the other above-mentioned methods do not give the lock on the object immediately until the currently executing thread
completes the synchronized code. It is mostly used in synchronization.

Example:
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
Synchronized (t) {
Wait();
}
}

Q #43) Difference between notify() method and notifyAll() method in Java.


Answer: The differences between notify() method and notifyAll() method are enlisted below:
notify() notifyAll()

This method is used to send a signal to wake up a single This method sends the signal to wake up all the threads
thread in the waiting pool. in a waiting spool.
Q #44) How to stop a thread in java? Explain about sleep () method in a thread?
Answer: We can stop a thread by using the following thread methods:
 Sleeping
 Waiting
 Blocked
Sleep: Sleep () method is used to sleep the currently executing thread for the given amount of time. Once the thread is wake up it can
move to the runnable state. So sleep () method is used to delay the execution for some period.
It is a static method.

Example:
Thread. Sleep (2000)
So it delays the thread to sleep 2 milliseconds. Sleep () method throws an uninterrupted exception, hence we need to surround the block
with try/catch.

public class ExampleThread implements Runnable{


public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
}
}
Q #45) When to use the Runnable interface Vs Thread class in Java?
Answer: If we need our class to extend some other classes other than the thread then we can go with the runnable interface because in
java we can extend only one class.
If we are not going to extend any class then we can extend the thread class.

Q #46) Difference between start() and run() method of thread class.


Answer: Start() method creates a new thread and the code inside the run () method is executed in the new thread. If we directly called
the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method.
Q #47) What is Multi-threading?
Answer: Multiple threads are executed simultaneously. Each thread starts its own stack based on the flow (or) priority of the threads.
Example Program:
public class MultipleThreads implements Runnable
{
public static void main (String[] args){//Main thread starts here
Runnable r = new runnable ();
Thread t=new thread ();
t.start ();//User thread starts here
Addition add=new addition ();
}
public void run(){
go();
}//User thread ends here
}
On the 1st line execution, JVM calls the main method and the main thread stack looks as shown below.

Once the execution reaches, t.start () line then a new thread is created and the new stack for the thread is also created. Now JVM
switches to the new thread and the main thread are back to the runnable state.
The two stacks look as shown below.

Now, the user thread executed the code inside the run() method.

Once the run() method has completed, then JVM switches back to the main thread and the user thread has completed the task and the
stack was disappeared.

JVM switches between each thread until both the threads are completed. This is called Multi-threading.

Q #48) Explain the thread life cycle in Java.


Answer: Thread has the following states:
 New
 Runnable
 Running
 Non-runnable (Blocked)
 Terminated

 New: In New state, a Thread instance has been created but start () method is not yet invoked. Now the thread is not considered
alive.
 Runnable: The Thread is in the runnable state after the invocation of the start () method, but before the run () method is invoked.
But a thread can also return to the runnable state from waiting/sleeping. In this state, the thread is considered alive.
 Running: The thread is in a running state after it calls the run () method. Now the thread begins the execution.
 Non-Runnable(Blocked): The thread is alive but it is not eligible to run. It is not in the runnable state but also, it will return to the
runnable state after some time. Example: wait, sleep, block.
 Terminated: Once the run method is completed then it is terminated. Now the thread is not alive.
Q #49) What is Synchronization?
Answer: Synchronization makes only one thread to access a block of code at a time. If multiple threads access the block of code, then
there is a chance for inaccurate results at the end. To avoid this issue, we can provide synchronization for the sensitive block of codes.
The synchronized keyword means that a thread needs a key in order to access the synchronized code.

Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can access a synchronized method only if the
thread can get the key to the objects to lock.

For this, we use the “Synchronized” keyword.

Example:
public class ExampleThread implements Runnable{
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
synchronized(object){
{
}
}
Q #50) What is the disadvantage of Synchronization?
Ans: Synchronization is not recommended to implement all the methods. Because if one thread accesses the synchronized code then
the next thread should have to wait. So it makes a slow performance on the other end.
Q #51) What is meant by Serialization?
Answer: Converting a file into a byte stream is known as Serialization. The objects in the file are converted to bytes for security
purposes. For this, we need to implement a java.io.Serializable interface. It has no method to define.
Variables that are marked as transient will not be a part of the serialization. So we can skip the serialization for the variables in the file by
using a transient keyword.

Learn More =>> Serializable and Cloneable


Q #52) What is the purpose of a transient variable?
Answer: Transient variables are not part of the serialization process. During deserialization, the values of the transient variables are set
to the default value. It is not used with static variables.
Example:
transient int numbers;

Q #53) Which methods are used during the Serialization and Deserialization process?
Answer: ObjectOutputStream and ObjectInputStream classes are higher level java.io. package. We will use them with lower level
classes FileOutputStream and FileInputStream.
ObjectOutputStream.writeObject —->Serialize the object and write the serialized object to a file.
ObjectInputStream.readObject —> Reads the file and deserializes the object.
To be serialized, an object must implement the serializable interface. If superclass implements Serializable, then the subclass will
automatically be serializable.

Q #54) What is the purpose of a Volatile Variable?


Answer: Volatile variable values are always read from the main memory and not from thread’s cache memory. This is used mainly
during synchronization. It is applicable only for variables.
Example:
volatile int number;

Q #55) Difference between Serialization and Deserialization in Java.


Answer: These are the differences between serialization and deserialization in java:
Serialization Deserialization

Serialization is the process which is used to Deserialization is the opposite process of serialization where we
convert the objects into byte stream can get the objects back from the byte stream.

An object is serialized by writing it an An object is deserialized by reading it from an


ObjectOutputStream. ObjectInputStream.

Q #56) What is SerialVersionUID?


Answer: Whenever an object is Serialized, the object is stamped with a version ID number for the object class. This ID is called the
SerialVersionUID. This is used during deserialization to verify that the sender and receiver that are compatible with the Serialization.

Most Frequently Asked OOPS Interview Questions


Q #1) Explain in brief what do you mean by Object Oriented Programming in Java?
Answer: OOP deals with objects, like real-life entities such as pen, mobile, bank account which has state (data) and behavior
(methods).
With help of access, specifiers access to this data and methods is made secured. Concepts of encapsulation and abstraction offer
data hiding and access to essentials, inheritance, and polymorphism help code reuse and overloading/overriding of methods and
constructors, making applications platform-independent, secured and robust using languages like Java.

Q #2) Explain Is Java a pure Object Oriented language?


Answer: Java is not an entirely pure object-oriented programming language. The following are the reasons:
 Java supports and uses primitive data types such as int, float, double, char, etc.
 Primitive data types are stored as variables or on the stack instead of the heap.
 In Java, static methods can access static variables without using an object, contrary to object-oriented concepts.
Q #3) Describe class and object in Java?
Answer: Class and object play an integral role in object-oriented programming languages like Java.
 Class is a prototype or a template that has state and behaviour supported by an object and used in the creation of
objects.
 The object is an instance of the class,
 for example, Human is a class with the state as having a vertebral system, brain, color, and height and has behavior
such as canThink(), ableToSpeak(), etc.

Q #4) What are the differences between class and objects in Java?

Class Object
Class is a logical entity Object is physical entity
Class is a template from which object can be Object is an instance of the class
created
Class Object
Class is a prototype that has the state and Objects are entities that exist in real life such as mobile, mouse, or intellectual
behavior of similar objects objects such as bank account
Class is declared with class key word like class Object is created via new keyword as Employee emp = new Employee();
Classname { }
During class creation, there is no allocation of During object creation, memory is allocated to the object
memory
There is only one-way class is defined using Object creation can be done many ways such as using new keyword,
the class keyword newInstance() method, clone() and factory method.
Real-life examples of Class can be a Real-life examples of Object can be
•A recipe to prepare food. •A food prepared from recipe.
•Blue prints for an automobile engine. •Engine constructed as per blue-prints.

Q #5) Why is a need for Object-oriented programming?


Answer: Object-oriented programming (OOP) provides a powerful paradigm for organizing and structuring code by modeling
real-world entities as objects with properties (attributes) and behaviors (methods).
OOP provides access specifiers and data hiding features for more security and control data access, overloading can be achieved
with function and operator overloading, Code Reuse is possible as already created objects in one program can be used in other
programs.
Data redundancy, code maintenance, data security, and advantage of concepts such as encapsulation, abstraction, polymorphism,
and inheritance in object-oriented programming provide an advantage over previously used procedural programming languages.

Q #6) Explain Abstraction with a real-time example.


Answer: Abstraction in object-oriented programming means hiding complex internals but to expose only essential
characteristics and behaviour with respect to context.
How things happen is not what you are interested in, as it is complex and kept hidden. This is known as abstraction.
EX: In our Automation Framework whenever we Use the Page object Model, we write all the locators in the page class and use
this locator in our test it means we are hiding our implementation from the user this is a simple example of using abstraction in
the framework.

In real life, an example of abstraction is an online shopping cart, say at any e-commerce site. Once you select a product and book
order, you are just interested in receiving your product on time.
Similarly, take the example of ATM, the complexity of internals of how money is debited from your account is kept hidden, and
you receive cash via a network. Similarly for cars, how petrol makes the engine run the automobile is extremely complex.

Q #7) Give some real-time examples and explain Inheritance.


Answer: Inheritance means one class (sub class) acquiring properties of another class (super class) by inheritance. In real life,
take an example of inheritance of a normal bicycle where it is a parent class and a sports bike can be a child class, where sports
bike has inherited properties and behavior of rotating wheels with pedals via gears that of a normal bike.

Q #8) How polymorphism works in Java, explain with real-life examples?


Answer: Polymorphism is an ability to have multiple forms or capability of the method to do different things. In real life, the
same person performing different duties behaves differently.
 Runtime polymorphism: This is achieved by method overriding.
o The Bike class has a method called run() that simply prints "running" to the console. The Hayabusa class extends
the Bike class and overrides the run() method with its own implementation that prints "running safely" to the
console.
 Compile-time polymorphism: This is achieved by method overloading or operator overloading.
o the MathOperations class defines three add() methods, each with a different number or type of parameters. During
compile time, Java determines which add() method to call based on the arguments passed to it

EX: In-Office he is an employee, at home, he is a father, during or in after school tuitions he is a student, on weekends he plays
cricket and is a player in the playground.

Q #9) How many types of inheritance are present?


Answer: Various types of inheritance are listed below:
 Single Inheritance: Single child class inherits characteristics of the single-parent class.
 Multiple Inheritance: One class inherits features of more than one base class and is not supported in Java, but the
class can implement more than one interface.
 Multilevel Inheritance: A class can inherit from a derived class making it a base class for a new class, for
example, a Child inherits behavior from his father, and the father has inherited characteristics from his father.
 Hierarchical Inheritance: One class is inherited by multiple subclasses.
 Hybrid Inheritance: This is a combination of single and multiple inheritances.
Q #10) What is Interface?
Answer: Interface is similar to the class where it can have methods and variables, but its methods do not have a body, just a
signature known as the abstract method. Variables declared in the interface can have public, static, and final by default. Interface
is used in Java for abstraction and multiple inheritances, where the class can implement multiple interfaces.
Q #11) Can you explain the advantages of Abstraction and Inheritance?
Answer: Abstraction reveals only essential details to the user and ignores or hides irrelevant or complex details. In other words,
data abstraction exposes the interface and hides implementation details. Java performs abstraction with the help of interfaces and
abstract classes. Advantage of abstraction is that it makes simple in viewing things by reducing or hiding the complexity of
implementation.
Duplication of code is avoided, and it increases code reusability. Only essential details are revealed to the user and improves the
security of the application.

Inheritance is where child class inherits functionality (behaviour) of the parent class. We need not write code once written in
parent class for functionality again in the child class and thus making it easier to reuse the code. The code becomes readable as
well. Inheritance is used where there “is a” relation. Example: Hyundai is a car OR MS Word is a software.
Q #12) What is the difference between extends and implements?
Answer: Both extends and implements keyword are used for inheritance but in different ways.
The differences between Extends and Implements keywords in Java are explained below:
Extends Implements
A class can extend another class (child extending parent by inheriting his A class can implement an interface
characteristics). Interface as well inherit (using keyword extends) another interface.
Sub class extending super class may not override all of the super class methods Class implementing interface has to
implement all the methods of the interface.
Class can only extend a single super class. Class can implement any number of
interfaces.
Interface can extend more than one interfaces. Interface cannot implement any other
interface.
Syntax: Syntax:
class Child extends class Parent class Hybrid implements Rose
Q #13) What are different access modifiers in Java?
Answer: Access modifiers in Java controls access scope of class, constructor, variable, method, or data member. Various types
of access modifiers are as follows:
 Default access modifier is without any access specifier data members, class and methods, and are accessible
within the same package.
 Private access modifiers are marked with the keyword private, and are accessible only within class, and not even
accessible by class from the same package.
 Protected access modifiers can be accessible within the same package or subclasses from different packages.
 Public access modifiers are accessible from everywhere.
Q #14) Explain the difference between abstract class and method?
Answer: Following are some differences between abstract class and abstract method in Java:
Abstract Class Abstract Method
Object cannot be created from the abstract class. Abstract method has a signature but does not have a body.
Sub class created or inherit abstract class to access members of It is compulsory to override abstract methods of super class in
abstract class. their sub class.
Abstract class can contain abstract methods or non abstract Class containing abstract method should be made abstract class.
methods.
Q #15) What are the differences between method and constructor?
Answer: Following are the differences between constructors and methods in Java:
Constructors Methods
Constructors name should match with that of Class. Methods should not have same name as Class name.
They are used to create, initialize and allocate memory to the object. Methods are used to execute certain statements written
inside them.
Constructors are implicitly invoked by the system whenever objects are Methods are invoked when it is called.
created.
They are invoked using new keyword while creating an instance of the Methods are invoked during program execution.
class (object).
Constructor does not have return type. Method has a return type.
Constructor cannot be inherited by the subclass. Methods can be inherited by a sub class.
Q #16) What is a constructor in Java?
Answer: Constructor is a method without a return type and has its name the same as the class name. When we create an object, a
default constructor allocates memory for an object during the compilation of Java code. Constructors are used to initializing
objects and set initial values for object attributes.
Q #17) How many types of constructors can be used in Java? Please explain.
Answer: There are basically three types of constructors in Java.
These are:
1. Default constructor: This constructor is without any parameter and invokes every time you create an instance of a
class (object). If a class is an Employee, then the syntax of the default constructor will be Employee().
2. No-arg constructor: As the name implies, a constructor without any argument is called a no-arg constructor.
3. Parameterized constructor: Constructor with a number of parameters is called a parameterized constructor. You
are required to provide arguments, i.e. initial values with respect to the data type of parameters in that constructor.
Q #18) Why new keyword is used in Java?
Answer: When we create an instance of class, i.e. objects, we use the Java keyword new. It allocates memory in the heap area
where JVM reserve space for an object. Internally, it invokes the default constructor as well.
Syntax:
Class_name obj = new Class_name();
Q #19) When do you use the super keyword?
Answer: Super is a Java keyword used to identify or refer parent (base) class.
 We can use super to access super class constructor and call methods of the super class.
 When method names are the same in super class and sub class, to refer super class, the super keyword is used.
 To access the same name data members of parent class when they are present in parent and child class.
 Super can be used to make an explicit call to no-arg and parameterized constructors of the parent class.
 Parent class method access can be done using super, when child class has method overridden.
Q #20) When do you use this keyword?
Answer: this keyword in Java refers to the current object in the constructor or in the method.
 When class attributes and parameterized constructors both have the same name, this keyword is used.
 Keywords this invokes the current class constructor, method of the current class, return the object of the current
class, pass an argument in the constructor, and method call.
Q #21) What is the difference between Runtime and compile-time polymorphism?
Answer: Both runtime and compile-time polymorphism are two different types of polymorphism. Their differences are
explained below:
Compile Time Polymorphism Runtime Polymorphism
Call is resolved by a compiler in compile-time polymorphism. Call is not resolved by the compiler in runtime
polymorphism.
It is also known as static binding and method overloading. It is also known as dynamic, late, and method overriding.
Same name methods with different parameters or methods with the Same name method with the same parameters or signature
same signature and different return types are compile-time associated in different classes are called method
polymorphism. overriding.
It is achieved by function and operator overloading. It can be achieved by pointers and virtual functions.
As all the things are executed at compile time. compile-time As things execute at run time, runtime polymorphism is
polymorphism is less flexible. more flexible.
Q #22) What object-oriented features are used in Java?
Answer: A concept of using an object in Java programming language benefits by the use of object-oriented concepts like
encapsulation for binding together the state and behavior of an object, secures data access with access specifiers, features like
abstraction in information hiding, inheritance to extend state, and behavior of base classes to child classes, compile-time and
runtime polymorphism for method overloading and method overriding, respectively.
Q #23) What is method overloading?
Answer: When two or more methods with the same name have either a different number of parameters or different types of
parameters, these methods may have or may not have different return types, then they are overloaded methods, and the feature is
method overloading. Method overloading is also called compile-time polymorphism.
Q #24) What is method overriding?
Answer: When a method of sub class (derived, child class) has the same name, parameters (signature), and same return type as
the method in its super class (base, parent class) then the method in the subclass is said to be overridden the method in the
superclass. This feature is also known as runtime polymorphism.
Q #25) Explain constructor overloading.
Answer: More than one constructor having different parameters so that different tasks can be carried out with each constructor
is known as constructor overloading. With constructor overloading, objects can be created in different ways. Various Collection
classes in Java API are examples of constructor overloading.
Q #26) What types of arguments can be used in Java?
Answer: For Java methods and functions, parameter data can be sent and received in different ways. If methodB() is called from
methodA(), methodA() is a caller function and methodB() is called function, arguments sent by methodA() is actual arguments
and parameters of methodB() is called formal arguments.
 Call By Value: Changes made to formal parameter (parameters of methodB()) do not get sent back to the caller
(methodA()), This method is called call by value. Java supports the call by value.
 Call by Reference: Changes made to formal parameter (parameters of methodB()) are sent back to the caller
(parameters of methodB()).
 Any changes in formal parameters (parameters of methodB()) are reflected in actual parameters (arguments sent by
methodA()). This is called call by reference.
Q #27) Differentiate between static and dynamic binding?
Answer: The differences between Static and Dynamic binding are explained in the below table.
Static Binding Dynamic Binding
Static binding in Java use type of fields and class to as a resolution. Dynamic binding in Java uses object for resolving
binding.
Method Overloading is an example of static binding. Method overriding is an example of dynamic binding.
Static binding gets resolved at compile time. Dynamic binding gets resolved at run time.
Methods and variables using static binding are private, final and static Virtual methods use dynamic binding.
types.
Q #28) Can you explain base class, subclass, and superclass?
Answer: Base class, sub class, and super class in Java are explained as follows:
 Base class or parent class is a super class and is a class from which sub class or child class is derived.
 Sub class is a class that inherits attributes (properties) and methods (behaviour) from the base class.
Q #29) Is Operator overloading supported in Java?
Answer: Operator overloading is not supported by Java as,
It makes the interpreter put more effort to understand the actual functionality of the operator making code complex

and difficult to compile.
 Operator overloading makes programs more error-prone.
 However, the feature of operator overloading can be achieved in method overloading in a simple, clear, and error-
free way.
Q #30) When the finalize method is used?
Answer: finalize method is called just before the object is about to be garbage collected. This method overrides to minimize
memory leaks, undertake clean-up activities by removing system resources.
Q #31) Explain about Tokens.
Answer: Tokens in the Java program are the smallest elements that the compiler recognizes. Identifiers, keywords, literals,
operators, and separators are examples of tokens.

1. Explain Java Main Method public static void main (String[] args)
When you start learning Java, the first method you encounter is public static void main(String [] args). The starting
point of any Java Program is the main() method. It is one of the important methods of Java. Technically, the main method
is the starting point where the Java program starts its execution. JVM always look for this method signature to start
running an application. Check this to know detailed explanation.

2. What is Java?
Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of
applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast,
secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet,
Java is everywhere!

Java program which prints Hello World!

public class MyClass {


public static void main(String args[]) {
System.out.println("Hello World!");
}
}

3. Mention some features of Java?


Some of the features which play an important role in the popularity of java are as follows:

 Simple: Java is easy to learn. Even though Java is based on C++ , it was developed by eliminating poor
programming practices of C++.
 Object-Oriented: Java is an object-oriented programming language. Everything in Java is an Object.

Learn more here.

 Portable: Java run time environment uses a bytecode verification process to make sure that code loaded over the
network doesn’t violate Java security constraints.
 Platform independent: Java is platform-independent. Java is a write once, run anywhere language. Without any
modifications, we can use a program on different platforms.
 Secured: Java is well known for its security. It delivers virus-free systems.
 High Performance: Java enables high performance with the use of JIT (Just-In-Time) compilers
 Multithreaded: Java Multithreaded features allows us to write programs that can perform many tasks
simultaneously. The multithreading concept of Java shares a common memory area. It doesn’t occupy memory for
each thread.

4. Is Java 100% Object Oriented Language?


Java is not a pure Object Oriented Language because it supports primitive data type such as byte, boolean, char, double,
float, int, long, short. These primitive data types are not object oriented. This is the reason why Java is not 100% object-
oriented language.
5. What is the difference between Object-oriented programming language and
Object-based programming language?
There is a difference between Object Oriented Languages and Object Based languages.

Object Oriented Languages:

 Some of the Object Oriented Languages are Java, C#, VB. Net, Smalltalk etc.,
 These languages support all the concepts of OOPs.
 These languages don’t have the inbuilt objects.

Object Based Languages:

 Some of the Object Based Languages are JavaScript, VBScript etc.,


 These languages support all the concepts of OOPs like inheritance and polymorphism.
 These languages have the inbuilt objects, say JavaScript has window object.

6. What is the difference between Declaration and Definition in Java?


Declaration: If you just declare a class or method/function or variable without mentioning anything about what that class
or method/function or variable looks like is called a declaration in Java.

Definition: If you define how a class or method/function or variable is implemented then it is called definition in Java.

When we create an interface or abstract class, we simply declare a method/function but not define it.

For a clear understanding, check the below image

7. What is JRE, and why is it required?


JRE stands for “Java Runtime Environment”. It comprises of the JVM (Java Virtual Machine), Java platform classes, and
supporting libraries.
Using JRE, we can only execute already developed applications. We cannot develop new applications or modify existing
applications.
As the name suggests, JRE only provides Runtime Environment.

8. What is JDK, and why is it required?


JDK stands for Java Development Kit. It is a superset of JRE (Java Runtime Environment).
Using JDK, we can develop, compile and execute (run) new applications and also we can modify existing applications. We
need to install JDK in developers machine where we want to develop new applications or modify existing applications.
JDK includes JRE and development tools (environment to develop, debug and monitor Java programs).

9. What is JVM, and why is it required?


JVM stands for Java Virtual Machine. JVM drives the java code. Using JVM, we can run java byte code by converting them
into current OS machine language. It makes Java to become a portable language (write once, run anywhere)

10. What is an Object in Java?


An object is an instance of a class. Objects have state (variables) and behavior (methods).

Example: A dog is an object of Animal class. The dog has its states such as color, name, breed, and behaviors such as
barking, eating, wagging her tail.

public class MyClass{ //Class name (MyClass) declaration


public static void main(String[] args){
MyClass obj = new MyClass(); //Object Creation
}
}

11. What is a Class in Java?


A class can be defined as a collection of objects. It is the blueprint or template that describes the state and behavior of an
object.

public class MyClass{ //Class name (MyClass) declaration


int a = 9; // Variable declaration
int b = 99;
public void myMethod(){ //Method (myMethod) declaration
int sum=a+b;
}
}

12. What is Constructor in Java?


Constructor in Java is used in the creation of an Object that is an instance of a Class. The constructor name should be the
same as the class name. It looks like a method but it’s not a method. It won’t return any value. We have seen that
methods may return a value. If there is no constructor in a class, then the compiler automatically creates a default
constructor.

13. What is Local Variable and Instance Variable?


Local Variable:

A local variable is a variable that we declare inside a Method. A method will often store its temporary state in local
variables.

It can be accessible only inside a block, function, or constructor.

public void website() {


String websiteName;
double websiteLoadTime;
int webisteAge;
}
String websiteName, double websiteLoadTime, int websiteAge are Local variables in above example.

Instance Variable (Non-static):

An instance variable is a variable that is declared inside a Class but outside a Method. We don’t declare this variable as
Static because these variables are non-static variables.

It can be accessible by all the methods in the class.

class website() {
public String websiteName;
public double websiteLoadTime;
public int webisteAge;
}
websiteName, websiteLoadTime, websiteAge are Instance variables in above example.
Read more about Variables in Java here

14. What are the OOPs concepts?


OOPS Stands for Object-Oriented Programming System. It includes Abstraction, Encapsulation, Inheritance,
Polymorphism, Interface, etc.,

Read more on OOPs concept in Java

15. What is Inheritance in Java?


Inheritance is a process where one class inherits the properties (methods & fields) of another class. Read more here

16. What is Polymorphism?


Polymorphism allows us to perform a task in multiple ways. Let’s break the word Polymorphism and see it, ‘Poly’ means
‘Many’ and ‘Morphos’ means ‘Shapes’. Read more here
Assume we have four students and we asked them to draw a shape. All the four may draw different shapes like Circle,
Triangle, and Rectangle.

17. What are the types of Polymorphism?


There are two types of Polymorphism in Java

1. Compile time polymorphism (Static binding) – Method overloading


2. Runtime polymorphism (Dynamic binding) – Method overriding

We can perform polymorphism by ‘Method Overloading’ and ‘Method Overriding’

18. What is Method Overloading?


A class having multiple methods with the same name but different parameters are called Method Overloading

There are three ways to overload a method.

 Parameters with different data types


 Parameters with a different sequence of data types
 Different number of parameters

Read more on Method Overloading in Java

19. What is Method Overriding?


Declaring a method in child class that is already present in the parent class is called Method Overriding.

In simple words, overriding means to override the functionality of an existing method.

In this case, if we call the method with the child class object, then the child class method is called. To call the parent class
method we have to use super keyword.

Read more on Method Overriding

20. What is Abstraction in Java?


Abstraction is the methodology of hiding the implementation of internal details and showing the functionality to the
users.

Example: Mobile Phone.


A layman who is using a mobile phone doesn’t know how it works internally but he can make phone calls.

21. What is Abstract Class in Java?


We can easily identify whether a class is an abstract class or not. A class that contains abstract keyword in its declaration
then it is an Abstract Class.

Syntax:

abstract class <class-name>{}


Points to remember:

 Abstract classes may or may not include abstract methods


 If a class is declared abstract then it cannot be instantiated.
 If a class has abstract method then we have to declare the class as abstract class
 When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods
in its parent class. However, if it does not, then the subclass must also be declared abstract.

22. What is Abstract Method?


An abstract method is a method that is declared without an implementation (without braces, and followed by a
semicolon), like this:

abstract void myMethod();


In order to use an abstract method, you need to override that method in sub class.

23. What is Interface in Java?


An interface in Java looks similar to a class but both the interface and class are two different concepts. An interface can
have methods and variables just like the class but the methods declared in interface are by default abstract. We can
achieve 100% abstraction and multiple inheritance in Java with Interface. Read more on Interface in Java.

24. What is Encapsulation in Java?


Encapsulation is a mechanism of binding code and data together in a single unit. Let’s take an example of Capsule.
Different powdered or liquid medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and
variables are wrapped together in a single class. Read more on Encapsulation in Java

25. What is String in Java?


String in Java is an object that represents sequence of characters. An array of characters works same as Java string. String
in Java is an immutable (cannot grow) object that means it is constant and cannot be changed once it is created.

For example:

char[] c={‘S’,’T’,’M’};
26. Why are strings immutable in Java?
In Java, String is immutable to make sure that the string value doesn’t change. String literals are usually shared between
multiple clients. If the value of the string changes (from “STM” to “stm”), it will affect all reference variables and cause
severe discrepancies.
Hence, strings are immutable in Java. Making string immutable enhances security, caching, synchronization, and
performance of the application.

27. What is the difference between equals() method and double equal operator
(==) in Java?
equals() method

 This method is defined in the Object class in Java.


 It is used for checking the equality of contents between two objects defined by business logic.
 public boolean equals(Object o) is the method provided by the Object class.

double equal operator (==)

 It is a binary operator in Java.


 It is used for comparing addresses (or references), i.e checks if both the objects are pointing to the same memory
location.
 Default implementation uses double equal operator == to compare two objects.

28. How to convert Integer to String in Java?


package softwareTestingMaterial;

public class STM {

public static void main(String[] args) {


int x = 123;
int y = 456;
String s1 = Integer.toString(x);
String s2 = Integer.toString(y);
System.out.println(""String s1 = "" + s1);
System.out.println(""String s2 = "" + s2);
}
}

29. How to convert String to Integer in Java?


package softwareTestingMaterial;

public class STM {

public static void main(String[] args) {


String str = ""100"";
// Integer.parseInt()
System.out.println( Integer.parseInt( str ));
}
}

30. How to convert Char to Integer in Java?


package softwareTestingMaterial;

public class STM {

public static void main(String[] args) {


// Initializing a character(ch)
char c = '9';
// Converting the character to an interger value
int number = Integer.parseInt(String.valueOf(c));
System.out.println(number);
}
}

31. Write a program to print the pattern given below


1
12
123
1234
12345
Here is the program to print the pattern mentioned above

package softwareTestingMaterial;

public class NumberPattern {

public static void main(String[] args) {


for (int x = 1; x <= 5; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y+" ");
}
System.out.println();
}
}
}

32. Write a program to print the pattern given below (Left Triangle Star Pattern)
*
**
***
****
*****
Here is the program to print the pattern mentioned above

package softwareTestingMaterial;

public static void main(String args[])


{
//x for rows, y for columns, and row denotes the number of rows to print
int x, y, row=5;
//outer loop for rows
for(x=0; x<row; x++)
{
//inner loop for columns
for(y=0; y<=x; y++)
{
//To prints stars
System.out.print("* ");
}
//Cursor goes to the new line after printing each line.
System.out.println();
}
}
}

33. Write a program to print the pattern given below (Right Triangle Star Pattern)
*
**
***
****
*****
Here is the program to print the pattern mentioned above

package softwareTestingMaterial;

public static void main(String args[])


{
//x for rows, y for columns, and row denotes the number of rows to print
int x, y, row=5;
//outer loop for number of rows
for(x=0; x<row; x++)
{
//inner loop for columns
for(y=2*(row-x); y>=0; y--)
{
//To prints spaces
System.out.print(" ");
}
//Inner loop for columns
for(y=0; y<=x; y++)
{
//To prints stars
System.out.print("* ");
}
//Cursor goes to the new line after printing each line
System.out.println();
}
}
}

34. Write a program to print the pattern given below (Pyramid Star Pattern)
*
**
***
****
*****
Here is the program to print the pattern mentioned above

public static void main(String args[])


{
//x for rows, y for columns, and row denotes the number of rows to print
int x, y, row = 5;
//Outer loop for rows
for (x=0; x<row; x++)
{
//inner loop for space
for (y=row-x; y>1; y--)
{
//To print space between two stars
System.out.print(" ");
}
//inner loop for columns
for (y=0; y<=x; y++ )
{
//To print star
System.out.print("* ");
}
//Cursor goes to the new line after printing each line.
System.out.println();
}
}

35. Write a program to print Fibonacci Series up to count 10.


package softwareTestingMaterial;

public class FibonacciSeries {

public static void main(String args[]) {


int a = 0, b = 1, c, i, count = 10;
// To print 0 and 1
System.out.print(a + " " + b);
// loop starts from 2. We have already printed 0 and 1 in the previous step
for (i = 2; i < count; i++) {
c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
}
}

36. How to reverse a String in Java?


package softwareTestingMaterial;

public class ReverseString {

public static void main(String[] args) {


// Using StringBuffer class
StringBuffer a = new StringBuffer("Software Testing Material");
// use reverse() method to reverse string
System.out.println(a.reverse());
}

}
Another method:

package softwareTestingMaterial;

public class ReverseString {

public static void main(String[] args) {


String input="Software Testing Material";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1=input1.reverse();
for (int i=0;i<input1.length();i++)
System.out.print(input1.charAt(i));
}

}
Check this for other methods we use to reverse a String in Java

37. How To Find The Largest Value From The Given Array.
package softwareTestingMaterial;
public class LargestValue {

public static void main(String[] args){

int[] arr={28,3,15,9,17,4,23,2};

int val=arr[0];

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


if(arr[i] > val){
val=arr[i];
}
}
System.out.println("Largest value in the Given Array is "+ val);
}
}

38. How to display all the prime numbers between 1 and 100
The number which is only divisible by 1 and itself is known as a prime number. For example 2, 3, 5, 7, 11… are prime
numbers.

package softwareTestingMaterial;

public class PrimeNumbersOneToHundred {


public static void main (String[] args){
int i =0;
int num =0;
String primeNumbers = "";

for (i = 1; i <= 100; i++){


int counter=0;
for(num =i; num>=1; num--){
if(i%num==0){
counter = counter + 1;
}
}
if (counter ==2){
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}

39. How to display all the prime numbers between 1 and n (n is the number, get
the input from user)
package softwareTestingMaterial;

import java.util.Scanner;

public class PrimeNumbersOneToN {


public static void main (String[] args){
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
String primeNumbers = "";
System.out.println("Enter the value of n :");
int n = scanner.nextInt();
scanner.close();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
40. How to find the given number is a prime number or not by getting input from
the user
package softwareTestingMaterial;

import java.util.Scanner;

public class PrimeNumberVerification {


public static void main(String args[])
{
int i, j, flag = 0;
System.out.print("Enter any number which you want to verify whether it is a prime number or not :");
Scanner s = new Scanner(System.in);
j = s.nextInt();
for( i = 2; i < j; i++){
if(j % i == 0){
flag = 0;
break;
}
else
{
flag = 1;
}
}
if(flag == 1){
System.out.println(j+" is a prime number.");
}
else{
System.out.println(+j+" is not a prime number.");
}
}
}

41. Write a program to print Fibonacci Series


Method 1:

package softwareTestingMaterial;

public class FibonacciSeries {

public static void main(String args[]) {


int a = 0, b = 1, c, i, count = 10;
// To print 0 and 1
System.out.print(a + " " + b);
// loop starts from 2. We have already printed 0 and 1 in the previous step
for (i = 2; i < count; i++) {
c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
}
}
Method 2:

package softwareTestingMaterial;

import java.util.Scanner;

public class FibonacciSeriesOne {


public static void main(String[] args){
System.out.println("Enter Iteration to print Fibonacci Series");
FibonacciCheck.checkFibonacci(new Scanner(System.in).nextInt());
}
}

class FibonacciCheck {
public static void checkFibonacci(int number){
int first=0,second=1;
int third=0;
int i=1;
System.out.print("Fibonacci Series upto: "+number+" is ");
System.out.print(first+","+second+",");
while(i<=number){
third=first+second;
System.out.print(third+",");
first=second;
second=third;
++i;
}
}
}
42. How to read a file line by line in Java?
We can read a file line by line in Java in two ways.

1. BufferedReader Class
2. Scanner Class

Using BufferedReader Class:

BufferedReader Class belongs to java.io package and it provides readLine() method to read a file line by line in Java.

package softwareTestingMaterial;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadLineByProgram {

public static void main(String[] args) {


BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"/Users/Rajkumar/Downloads/STM.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using Scanner Class:

Java Scanner class provides the nextLine() method to facilitates line by line of file’s content.

package softwareTestingMaterial;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadLineByProgram {

public static void main(String[] args) {


try {
Scanner scanner = new Scanner(new File("/Users/Rajkumar/Downloads/STM.txt"));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

43. Difference between Array and ArrayList?


Array ArrayList

Array is static ArrayList is dynamic

Size of the array may not be required. It changest the size


Size of the array should be given at the time of array declaration.
dynamically. Capacity of ArrayList increases automatically
We cannot change the size of array after creating it
whenever we add elements to an ArrayList

ArrayList cannot contain primitive data types. It contains


Array can contain both primitive data types as well as objects
only objects

Arrays are multidimensional ArrayList is always single dimension

44. Difference between ArrayList and HashSet in Java?


ArrayList HashSet

ArrayList implements List interface HashSet implements Set interface

ArrayList allows duplicates HashSet doesn’t allow duplicates

ArrayList is an ordered collection and maintains insertion order HashSet is an unordered collection and doesn’t maintain
of elements insertion order

ArrayList is backed by an Array HashSet is backed by an HashMap instance

ArrayList is an index based HashSet is object based

In ArrayList, we can retrive object by calling get() method or


In HashSet, we can’t achieve get() method
remove object by calling remove() method

Learn more on Array and ArrayList with sample programs

45. What are the different access modifiers available in Java?


Access modifiers are subdivided into four types such as Default, Public, Private, Protected

default: The scope of default access modifier is limited to the package only. If we do not mention any access modifier,
then it acts like a default access modifier.

private: The scope of private access modifier is only within the classes.

Note: Class or Interface cannot be declared as private

protected: The scope of protected access modifier is within a package and also outside the package through inheritance
only.

Note: Class cannot be declared as protected

public: The scope of public access modifier is everywhere. It has no restrictions. Data members, methods and classes that
declared public can be accessed from anywhere.

See some sample programs of access modifiers

46. Difference between static binding and dynamic binding?


1. Static binding is also known as early binding whereas dynamic binding is also known as late binding.
2. Determining the type of an object at compile time is Static binding whereas determining the type of an object at run
time is dynamic binding
3. Java uses static binding for overloaded methods and dynamic binding for overridden methods.

To know more about this you have to go through Method Overloading and Method Overriding.

47. Difference between Abstract Class and Interface?


ABSTRACT CLASS INTERFACE

To declare Abstract class we have to use abstract keyword To declare Interface we have to use interface keyword

In an Interface keyword abstract is optional to declare a


In an Abstract class keyword abstract is mandatory to declare a
method as an abstract. Compiler treats all the methods as
method as an abstract
abstract by default

An abstract class contains both abstract methods and concrete


An interface can have only abstract methods
methods(method with body)

An abstract class provides partial abstraction An interface provides fully abstraction

An abstract class can have public and protected abstract methods An interface can have only public abstract methods

An abstract class can have static, final or static final variables with
An interface can have only public static final variables
any access modifiers

An abstract class can extend one class or one abstract class An interface can extend any number of interfaces

Abstract class doesn't support multiple inheritance Interface supports multiple inheritance

48. What is Multiple Inheritance?


If a class implements multiple interfaces, or an interface extends multiple interfaces then it is known as multiple
inheritance.

49. What are the differences between throw and throws in Java?
throw keyword

 The throw keyword is used to explicitly throw an exception in the program inside a function or inside a block of
code.
 The checked exceptions cannot be propagated with throw only.
 The throw keyword is followed by an instance.
 The throw keyword is used within the method.
 You cannot throw multiple exceptions.

throws keyword

 The throws keyword is used in the method signature to declare an exception which might get thrown by the
function while executing the code.
 The checked exception can be propagated with throws
 The throws keyword is followed by class.
 The throws keyword is used with the method signature.
 You can declare multiple exceptions, e.g., public void method()throws IOException, SQLException.

We will update this post “Java Interview Questions For Selenium Testers” ASAP. Keep visiting.

Common test automation interview questions & topics one can expect for 5+ years experience

Java-Basic
1. Types of polymorphism
2. Difference between override and overload
3. Methods that cannot be overloaded
4. Static block and instance block
5. Difference in Static and non static
6. Encapsulation and common use cases
7. Abstract vs interfaces
8. Inheritance in java
9. Methods that cannot be overloaded
10. Type casting in java
11. String buffer and string builder
12. Why string is immutable in java
13. How to handle exceptions
14. Can I write try catch without the catch block
15. Difference between throws and throw
16. Use of iterator in java
17. Difference in Final, finally and finalize
18. Boxing and unboxing in java
19. Increment and decrement operation
20. Variable Args
21. This and super keyword in java
22. Issues during Swtich case without break
23. Upcasting and downcasting
24. Baseclass of all class in java
25. Baseclass of error and exceptions
26. Access specifiers
27. Continue and break statement
28. Can main method return any value
29. Can we overload main method. What happens when overloaded
30.how to execute and statement before main method
31. Difference between == and equals()
32. Can user declare constructor as final
33. Can we cast any other type to Boolean data with type casting.
34.does java compile if user use 'static public void' instead of 'public static void'
35.can we use this() and super() in a constructor
36. Can we create object of abstract class
37. Can we create reference for an abstract class
38. Can we declare a class as static
39. What is instanceOf keyword
40. What's the load factor of HashMap
41. How to prevent a class from being sub classes
42. Final variable, final method and final class
43. Ways to create a string variable.
44. What is gc() - garbage collector
45. Subclass and innerclass
46. Infinite loop in java
47. How to make copy of an element
48. Checked and unchecked exceptions

Java Collection
1. Classes inside List interface, Set interface, Map Interface
2. Arraylist vs Linkedlist
3. Arraylist vs array
4. Arraylist vs vector or stack
5. Which class of List Interface to be used if user have more insertions and deletions
6. Which class of List Interface to be used if user have more retrieval
7. Set Interface: HashSet, TreeSet, SortedSet
8. Map - HashMap, HashTable, TreeMap, LinkedHashMap.
9. Stack and Queue
10. How to maintain insertion order in Set, List and Map
11. How to sort elements in ascending order in Set and Map

Java Programs
1. String reverse
2. String Palindrome
3. String Anagram
4. Find occurrences of characters in a string
5. Find the count of Capital and Small letters in a string
6. Remove duplicate characters from string
7. Swap to numbers without temporary variable
8. Reverse number
9. factorial
10. Fibonacci
11. Count number, alphabet and special characters

Change request - bug fixes


Feature Request - comes from customer for some enhansment

What re collections used in project


what is final keyword in java - use of final , class-cannot extend, method cannot ovverride, variable cannot reassign value
difference between final and finally - final is keyword and finally is block used during exception handling
find largest between two number without using if condition - user ternsry concept like {int large = a>b?a:b;}
find the character in Uppper case and lowercase in string

meaning of webdriver driver = new Chromedriver(); where, Webdriver is Interface, driver is reference variable, New is keyword to create
variable and Chromedriver is construtor.

Use of implicite and explicite wait, expected conditions in explicite wait.

1) Tell me about yourself?


2) How you developed a framework from scratch?
3) What is CI/CD?
4) What are different keywords used in feature file?
5) What is use of scenario outline keyword?
6) What is data table?
7) What are the 5 different HTTP methods in rest API?
6) What are the different type of locators?
7) What are the different type of annotations in hook class?
8) Suppose in a hook 2 before annotations are present , then which first before annotations will get executed and how?
9) What are the different types of assertion in Testng?
10) What is use of priority keyword?
11) How to create customer message using assert?
12) What is wrong in below Json object:
{
parameter ="CC",
amount=1000,
day ="Monday"

That's quite an extensive list of questions covering various aspects of Java programming! I'll provide brief answers to each:

1. Types of polymorphism: There are two types of polymorphism in Java: compile-time polymorphism (achieved through method overloading)
and runtime polymorphism (achieved through method overriding).
2. Difference between override and overload: Overriding involves creating a new implementation of a method in a subclass, while overloading
involves defining multiple methods in the same class with the same name but different parameters.
3. Methods that cannot be overloaded: Constructors and static methods cannot be overloaded.
4. Static block and instance block: Static blocks are executed when the class is loaded into memory, whereas instance blocks are executed each
time an instance of the class is created.
5. Difference in Static and non-static: Static members belong to the class itself, while non-static members belong to individual instances of the
class.
6. Encapsulation and common use cases: Encapsulation involves wrapping data and methods into a single unit. Common use cases include data
hiding, abstraction, and access control.
7. Abstract vs interfaces: Abstract classes can have constructors and non-abstract methods, while interfaces cannot. Classes can implement
multiple interfaces but can only extend one abstract class.
8. Inheritance in Java: Inheritance allows a class to inherit properties and behavior from another class. It promotes code reusability and is a
fundamental concept of OOP.
9. Methods that cannot be overloaded: Constructors and static methods cannot be overloaded.
10. Type casting in Java: Type casting is the process of converting one data type into another. It can be done implicitly or explicitly.
11. String buffer and string builder: Both are used to manipulate strings, but StringBuffer is thread-safe whereas StringBuilder is not.
12. Why string is immutable in Java: Strings are immutable in Java for security, concurrency, and performance reasons. Immutable strings are
also thread-safe.
13. How to handle exceptions: Exceptions can be handled using try-catch blocks or by declaring them in the method signature using the throws
keyword.
14. Can I write try catch without the catch block: Yes, you can write a try-catch block without the catch block, but you must include either a
finally block or declare the exception to be thrown using the throws keyword.
15. Difference between throws and throw: "throws" is used to declare an exception that a method might throw, while "throw" is used to
explicitly throw an exception within a method.
16. Use of iterator in Java: Iterators are used to traverse collections like ArrayList, LinkedList, etc., allowing sequential access to elements.
17. Difference in Final, finally, and finalize: "final" is a keyword used to declare constants, "finally" is a block used to execute code after a try-
catch block, and "finalize" is a method called by the garbage collector before reclaiming an object's memory. "final" is a keyword used to declare
constants or make methods, classes, or variables immutable, "finally" is a block used to execute code after a try-catch block regardless of
whether an exception is thrown or not, and "finalize" is a method called by the garbage collector before reclaiming an object's memory.
18. Boxing and unboxing in Java: Boxing is the process of converting a primitive type to its corresponding wrapper class, and unboxing is the
reverse process.
19. Increment and decrement operation: In Java, the ++ operator increments the value by 1, and the -- operator decrements the value by 1.
20. Variable Args: Variable arguments allow methods to accept a variable number of arguments of the same type.
21. This and super keyword in Java: "this" refers to the current instance of a class, while "super" refers to the superclass of the current instance.
22. Issues during Switch case without break: Without "break" statements in a switch case, control will fall through to subsequent cases,
potentially leading to unintended behavior.
23. Upcasting and downcasting: Upcasting involves converting a subclass reference to a superclass reference, while downcasting involves the
reverse process. Downcasting requires explicit typecasting and may result in ClassCastException if done incorrectly.
24. Base class of all class in Java: The base class of all classes in Java is the Object class.
25. Base class of error and exceptions: Both errors and exceptions in Java are subclasses of the Throwable class.
26. Access specifiers: Access specifiers (public, private, protected, default) control the visibility and accessibility of classes, methods, and
variables in Java.
27. Continue and break statement: "continue" is used to skip the remaining code inside a loop and continue with the next iteration, while "break"
is used to exit the loop or switch statement.
28. Can main method return any value: No, the main method in Java does not return any value.
29. Can we overload main method. What happens when overloaded: Yes, you can overload the main method. However, only the main method
with the signature `public static void main(String[] args)` is executed by the JVM.
30. How to execute a statement before the main method: You can execute statements before the main method by placing them in a static block
within the class.
31. Difference between == and equals(): "==" is used to compare the references of objects, while "equals()" is used to compare the content or
values of objects.
32. Can user declare constructor as final: No, constructors cannot be declared as final. attempting to declare a constructor as final will result in a
compilation error in Java. However, you can achieve similar effects by making the class itself final, which would prevent it from being
subclassed and thus indirectly prevent any constructor overriding.
33. Can we cast any other type to Boolean data with type casting: No, Boolean cannot be cast to any other primitive data type and vice versa.
34. Does Java compile if user use 'static public void' instead of 'public static void': Yes, Java code will compile with either "public static void" or
"static public void" as they have the same effect.
35. Can we use this() and super() in a constructor: Yes, both "this()" and "super()" can be used in a constructor. "this()" calls another constructor
in the same class, and "super()" calls a constructor in the superclass.
36. Can we create an object of an abstract class: No, you cannot create an object of an abstract class. However, you can create references of an
abstract class type.
37. Can we declare a class as static: No, classes cannot be declared as static in Java.
38. What is instanceof keyword: The instanceof keyword is used to check whether an object is an instance of a particular class or interface.
39. What's the load factor of HashMap: The default load factor of HashMap in Java is 0.75.
40. How to prevent a class from being subclasses: To prevent a class from being subclassed, declare it as final.
41. Final variable, final method, and final class: "final" keyword is used to make variables, methods, or classes immutable or non-overridable.
42. Ways to create a string variable: Strings can be created using string literals, the new keyword, or by converting other data types to strings.
43. What is gc() - garbage collector: gc() is not a standard method in Java. The garbage collector is responsible for reclaiming memory by
destroying objects that are no longer referenced.
44. Subclass and innerclass: A subclass is a class that inherits from another class, while an inner class is a class defined within another class.
45. Infinite loop in Java: An infinite loop is a loop that continues indefinitely without terminating.
46. How to make a copy of an element: You can make a copy of an element by creating a new instance of the same type and copying the values
from the original element.
47. Checked and unchecked exceptions: Checked exceptions are checked at compile time, while unchecked exceptions are not.
1. What is the difference between POM and Page Factory?
Page Object Model (POM) is a design pattern for organizing page classes and their methods, Page Factory is a mechanism to initialize web
elements within those page classes more efficiently and with cleaner code. They are often used together to create robust and maintainable
automation frameworks.
1. Page Object Model (POM):
- In POM design pattern each web page of the application under test is represented as a separate class.
- Each page class contains the locators and methods to interact with the elements on that page.
- It promotes code reusability and reduces duplication by encapsulating the behavior of each page.
2. Page Factory:
- Page Factory enhances the implementation of the Page Object Model.
- It is a way to initialize the elements of a Page Object class automatically without using `findElement()` or `findElements()` methods
explicitly.
- Page Factory helps in improving the performance of tests by caching elements once they are located
- It centralizes the element initialization logic within the Page Object class.
2. What is Stale element?
Stale Element: A stale element is one that is no longer valid or usable. This can happen for various reasons:
The element has been removed from the DOM.
The page has been refreshed, causing the element to become stale.
The element has been modified in such a way that it is no longer the same element as when it was first located.
StaleElementReferenceException: This exception is thrown by Selenium WebDriver when you attempt to interact with a stale element. For
example, if you find an element and then the page gets refreshed, any reference to that element will become stale, and if you try to interact with
it, Selenium will throw a StaleElementReferenceException.
To handle this exception, you typically need to re-locate the element

3. What is Utility class


A utility class in Java is a class that contains only static methods and constants, and it typically provides common functionalities or helper
methods that are reusable across different parts of an application. Utility classes are often used to group related methods together and to promote
code reusability.

In the context of an automation framework, a utility class serves a similar purpose as it does in general Java programming—it provides common
functionalities and helper methods that are reusable across different parts of the framework. However, in an automation framework, utility
classes often include methods and functionalities specifically tailored for testing automation.

4. what are listeners in testNG


In TestNG, listeners are interfaces that allow you to customize the test execution flow and perform actions before or after certain events during
the test lifecycle. TestNG provides a set of predefined listeners that you can implement to add custom behavior to your tests.

5. What is collection in postman


In Postman, a collection is a group or container for a set of related API requests. It allows you to organize and manage your API requests in a
structured and hierarchical manner. Collections are essential for streamlining API testing, documentation, and collaboration within a team.
What are the different ways to share postman collection’s
There are several ways to share Postman collections, each suited to different collaboration scenarios and preferences. Here are the main methods:
1. Share via Public Link:
- Postman allows you to generate a public link for your collection. This link can be shared with anyone, even if they don't have a Postman
account.
- Recipients can view the collection and its documentation without logging in to Postman.
- Keep in mind that anyone with the link can access the collection, so use this option carefully for sensitive information.
2. Share with Team Members:
- If you're working within a team in Postman, you can share collections directly with team members.
- Team members can access shared collections within the Postman workspace, and you can control their permissions (e.g., view-only or edit
access).
3. Export/Import Collection File:
- You can export a collection as a file (in Collection v2 or JSON format) and share it with others.
- Recipients can import the collection file into their Postman workspace.
- This method is suitable for sharing collections outside of the Postman platform or for backup purposes.
4. Share via Postman API:
- Postman provides an API that allows you to programmatically share collections with others.
- You can retrieve the collection ID and construct a shareable link or perform other sharing actions programmatically.
5. Sync via Postman Cloud:
- If you and your collaborators are using Postman Cloud, collections can be synced automatically across team members' workspaces.
- Any changes made to the collection by one team member will be reflected in real-time for others.
6. Export as Swagger/OpenAPI Specification:
- If you want to share your API documentation with users who aren't using Postman, you can export your collection as a Swagger or OpenAPI
Specification file.
- This file can be used to generate API documentation or integrate with other API documentation tools.
7. Publish to Postman API Network:
- If your API is publicly available and you want to share it with a broader audience, you can publish your collection to the Postman API
Network.
- This allows other Postman users to discover and explore your API.
These are the primary methods for sharing Postman collections, each offering different levels of accessibility, control, and integration
capabilities. Choose the method that best suits your collaboration requirements and security considerations.

6. What are the method of finding the Dynamic Xpath?


Finding dynamic XPath expressions can be challenging because XPath expressions are often used to locate elements based on their static
properties such as IDs, class names, or attributes. However, there are strategies you can use to construct dynamic XPath expressions:
1. Using Contains: If an element's attribute contains a specific substring that remains constant, you can use the `contains()` function in XPath.
For example:
//input[contains(@id, 'dynamicId')]
2. Using Starts With: If an element's attribute starts with a specific substring, you can use the `starts-with()` function in XPath. For example:
//input[starts-with(@id, 'dynamicPrefix')]
3. Using Position: If an element's position relative to its siblings remains constant, you can use indexing in XPath. For example:
(//div[@class='dynamicClass'])[2]
4. Using Axes: XPath provides various axes that allow you to navigate the XML tree. For example:
- `following-sibling`: Selects siblings that come after the current node.
- `preceding-sibling`: Selects siblings that come before the current node.
- `parent`: Selects the parent of the current node.
- `ancestor`: Selects ancestors of the current node.
5. Using Logical Operators: You can combine multiple conditions using logical operators (`and`, `or`) in XPath. For example:
//input[contains(@id, 'dynamicId') and @class='inputClass']
6. Using Regular Expressions (Regex): Some programming languages or XPath implementations support regular expressions, allowing you to
use regex patterns to match dynamic attributes. However, this approach may not be universally supported across all XPath implementations.
When constructing dynamic XPath expressions, it's essential to consider the stability and uniqueness of the selector. Test your XPath expressions
thoroughly to ensure they reliably locate the intended elements across different scenarios and environments. Additionally, prefer using other
locator strategies such as CSS selectors whenever possible, as they may offer better performance and readability compared to XPath.

7. What is Data Driven framework


In automation testing, a data-driven framework is a testing approach where test data is separated from test scripts, allowing tests to be executed
with different sets of data without modifying the underlying code. This approach enhances the reusability, maintainability, and scalability of test
scripts by decoupling them from specific test data.
Here's how a data-driven framework typically works:
1. Test Data Source: Test data is stored separately from test scripts in external data sources such as Excel spreadsheets, CSV files, databases, or
JSON/XML files. These data sources contain input values, expected results, and other parameters needed for test execution.
2. Test Scripts: Test scripts are developed to read test data from the external data sources dynamically and use it to perform test actions. The test
scripts are designed to be generic and reusable, capable of working with different datasets.
3. Data-Driven Execution: During test execution, the test scripts retrieve test data from the external data sources and use it to drive the test
scenarios. For each iteration, the scripts use a new set of test data, enabling the same test script to be executed multiple times with different
inputs.
4. Parameterization: Test scripts are parameterized to accept input values and expected results dynamically from the external data sources. This
allows for flexibility and adaptability when executing tests with different datasets.
5. Reporting: Test execution results are logged or reported, indicating whether each test case passed or failed. Test reports may also include
details about the test data used for each iteration.
Benefits of Data-Driven Frameworks:
- Reusability: Test scripts can be reused with different datasets, reducing duplication of code and effort.
- Maintainability: Test data can be updated or modified independently of test scripts, making maintenance easier.
- Scalability: As the amount of test data grows, the framework can handle it efficiently without requiring significant changes to the underlying
code.
- Flexibility: Different combinations of test data can be used to execute the same test scenarios, providing comprehensive test coverage.
- Traceability: Test results can be correlated with specific datasets, providing traceability and helping identify patterns or trends.
Overall, data-driven frameworks are valuable in automation testing for their ability to streamline test execution, increase test coverage, and
improve the efficiency of testing processes.

8. Why were you using a data-driven framework? why not keyword-driven or other frameworks for automation.
The choice of automation framework depends on various factors such as project requirements, team expertise, scalability needs, and the nature
of the application under test. Each type of framework has its own strengths and weaknesses, and the decision to use a data-driven framework
over other frameworks like keyword-driven or modular frameworks depends on specific considerations:
1. Data-Driven Framework:
- When to Use: A data-driven framework is ideal when there is a need to execute the same test logic with multiple sets of input data.
- Advantages:
- Enhances test coverage by allowing the same test script to be executed with different datasets.
- Promotes maintainability by separating test data from test scripts, enabling easy updates and modifications to test data.
- Facilitates scalability as the framework can handle a large volume of test data efficiently.
- Example Scenario: Testing a web application with multiple user credentials, where the same set of test steps is performed with different
username/password combinations.
2. Keyword-Driven Framework:
- When to Use: A keyword-driven framework is suitable when there is a need for non-technical stakeholders to participate in test case creation
and maintenance.
- Advantages:
- Allows test cases to be written in a readable, domain-specific language using keywords and actions.
- Promotes collaboration between testers and domain experts by abstracting technical details.
- Facilitates code reuse by encapsulating common test actions as keywords.
- Example Scenario: Testing an e-commerce application where business analysts define test cases using keywords like "login," "search
product," and "add to cart."
3. Modular Framework:
- When to Use: A modular framework is useful when there is a need to organize test scripts into reusable modules or components.
- Advantages:
- Enhances maintainability by modularizing test scripts based on functional or logical components.
- Promotes reusability by allowing modules to be shared across different test cases or test suites.
- Facilitates parallel development as different team members can work on different modules independently.
- Example Scenario: Testing a banking application where test scripts are organized into modules such as "account management," "transaction
processing," and "report generation."
4. Hybrid Framework:
- When to Use: A hybrid framework combines the strengths of multiple frameworks and is suitable for complex automation projects with
diverse requirements.
- Advantages:
- Offers flexibility to choose the most appropriate approach (data-driven, keyword-driven, modular, etc.) based on specific testing scenarios.
- Adaptable to changing project requirements and evolving automation needs.
- Can leverage the benefits of different frameworks to address various challenges effectively.
- Example Scenario: Testing a healthcare application where a hybrid framework is used to combine data-driven testing for patient management
modules and keyword-driven testing for medical record management modules.
In summary, the choice of automation framework depends on the specific requirements, objectives, and constraints of the automation project.
Each framework has its own merits, and selecting the most suitable framework involves evaluating factors such as test complexity,
maintainability, scalability, and collaboration needs.

9. why we use "background" keyword in cucumber


In Cucumber, the `Background` keyword allows you to define a set of steps that are common to all scenarios in a feature file. It helps in reducing
redundancy by eliminating the need to repeat the same set of steps in every scenario.
Here are a few reasons why you might use the `Background` keyword in Cucumber:
1. Setup Steps: If your scenarios require certain setup steps to be executed before each scenario, you can define these steps in the `Background`
section. This ensures that the setup steps are executed consistently before every scenario in the feature file.
2. Common Preconditions: If your scenarios share common preconditions, such as logging in or navigating to a certain page, you can define
these steps in the `Background` section to avoid duplication across scenarios.
3. Improved Readability: Using the `Background` keyword improves the readability of your feature files by clearly separating the common setup
steps from the specific scenario steps. This makes it easier for stakeholders to understand the purpose of each scenario.
4. Maintainability: By centralizing common steps in the `Background` section, you make your feature files more maintainable. If the setup steps
change in the future, you only need to update them in one place, rather than modifying multiple scenarios.

10. What is runner class in cucumber ?


In Cucumber, a runner class is a Java class responsible for executing Cucumber features. It serves as an entry point for running Cucumber tests
and provides configurations for setting up the test environment, defining the location of feature files, and specifying which step definitions to
use.

11. What’s the real purpose of the runner class


The primary purpose of a runner class in Cucumber is to serve as an entry point for executing Cucumber tests and to configure various options
related to the test execution environment. Here's a detailed explanation of the real purposes of a runner class in Cucumber:
1. Execution Control: The runner class controls the execution of Cucumber tests. It specifies which feature files to run, which step definitions
(glue code) to use, and other runtime configurations.
2. Configuration Management: The runner class provides a centralized location to configure Cucumber options such as feature file location, glue
code packages, plugin options, and other runtime settings. This makes it easier to manage and maintain test configurations.
3. Integration with Test Frameworks: Runner classes integrate Cucumber with popular test frameworks such as JUnit or TestNG. They leverage
the capabilities of these frameworks to execute Cucumber tests and to generate test reports.
4. Reporting: The runner class may include configurations for generating test reports in various formats (e.g., HTML, JSON, XML). These
reports provide insights into test results, including passed, failed, or skipped scenarios, and help stakeholders analyze test coverage and identify
issues.
5. Parameterization: Runner classes support parameterization to customize test execution based on different configurations, environments, or test
suites. Parameters can be passed via command-line arguments, system properties, environment variables, or configuration files.
6. Integration with Build Tools: Runner classes are integrated with build automation tools such as Maven or Gradle to facilitate test execution as
part of the build process. They may also be integrated with Continuous Integration (CI) systems like Jenkins, Bamboo, or Azure DevOps for
automated testing.
7. Hooks and Setup/Teardown: Runner classes may contain hooks or setup/teardown methods to perform pre-test and post-test actions such as
setup, teardown, environment initialization, and cleanup. These actions ensure that the test environment is properly configured before test
execution and cleaned up afterward
Overall, the runner class in Cucumber plays a crucial role in orchestrating the execution of Cucumber tests, managing test configurations,
integrating with test frameworks and build tools, generating test reports, and providing a centralized location for controlling and customizing the
test execution process.

12. why you using parametrization in data driven


Parameterization in data-driven testing allows for the dynamic execution of test scenarios with different sets of input data. This approach is
particularly useful in data-driven testing because it enables the same test logic to be applied to multiple data sets without the need to duplicate
test scripts. Here's why parameterization is essential in data-driven testing:
1. Reusability: Parameterization allows test scripts to be reused with different input values, enhancing code reusability and reducing redundancy.
Instead of creating separate test scripts for each data set, you can define a single test script that accepts parameters and execute it with various
data sets.
2. Scalability: Data-driven testing often involves testing multiple combinations of input data to ensure comprehensive coverage.
Parameterization enables the scalability of test scenarios by accommodating a large number of test data sets without increasing the complexity of
test scripts.
3. Flexibility: With parameterization, test scenarios become more flexible and adaptable to changes in test data or requirements. You can easily
modify or update test data without modifying the underlying test logic, making test maintenance more manageable.
4. Test Coverage: By executing test scenarios with different input data, parameterization enhances test coverage by testing various boundary
conditions, edge cases, and scenarios that may not be covered by static test cases.
5. Data Separation: Parameterization facilitates the separation of test data from test scripts, aligning with the principles of data-driven testing.
Test data can be stored in external data sources such as Excel spreadsheets, CSV files, or databases, allowing for easy management and
maintenance.
6. Automation: In automated data-driven testing, parameterization enables the automation of test scripts to iterate through multiple data sets and
perform validations. Automation frameworks and tools provide mechanisms to parameterize test scripts and execute them with different input
data.
Overall, parameterization is fundamental in data-driven testing as it enables test scripts to be executed dynamically with various input data sets,
promoting reusability, scalability, flexibility, and comprehensive test coverage.

13. is it right statement that I can run data-driven using TestNg ?


Yes, it is absolutely correct that you can run data-driven tests using TestNG. TestNG provides built-in support for data-driven testing through its
data provider feature.
Here's how you can run data-driven tests using TestNG:
Data Provider: You define a method (usually annotated with @DataProvider) that supplies the test data to your test method. This method can
read data from various sources such as Excel sheets, CSV files, databases, or even hard-coded arrays.
Test Method: You write your test method, which receives the test data from the data provider as parameters. Inside the test method, you perform
your test actions using the supplied data.
TestNG Annotations: You use TestNG annotations to mark your test methods and configure the test execution behavior, such as dependencies,
grouping, parallel execution, and reporting.
Parameterization: TestNG automatically invokes your test method multiple times, once for each set of test data provided by the data provider.
This allows you to execute the same test logic with different input data sets.

14. What is Headless Browser Testing?


Headless browser testing refers to the practice of running web browser tests without the graphical user interface (GUI) being displayed. In other
words, the browser operates in a "headless" mode, where it runs in the background without rendering the content visually on the screen.
Here are some key points about headless browser testing:
1. No Graphical Interface: In headless mode, the browser operates without a graphical user interface. This means that users cannot see the web
pages being rendered or interact with them visually.
2. Automated Testing: Headless browser testing is commonly used for automated testing purposes, especially in scenarios where running tests in
a visible browser window is not necessary.
3. Performance and Efficiency: Running tests in headless mode can improve testing performance and efficiency because it eliminates the
overhead associated with rendering graphical content. This allows tests to execute faster and consume fewer system resources.
4. Continuous Integration: Headless browser testing is well-suited for integration into Continuous Integration (CI) pipelines, where automated
tests need to be executed frequently and efficiently without human intervention.
5. Cross-Browser Testing: Headless browsers can simulate different browser environments (such as Chrome, Firefox, or Safari) without actually
launching these browsers with their GUI. This enables cross-browser testing without the need to install and manage multiple browser versions.
6. Web Scraping and Automation: Headless browsers are also used for web scraping, data extraction, and automated tasks where accessing web
content programmatically is required without the need for a visible browser window.
Popular headless browser options include:
- Headless Chrome: A version of Google Chrome that runs without the GUI using the Chrome DevTools Protocol.
- Headless Firefox: A version of Mozilla Firefox that supports headless mode, allowing it to run without a graphical interface.
- PhantomJS: A headless browser scriptable with JavaScript, though it's being deprecated in favor of alternatives like Headless Chrome.
Overall, headless browser testing offers a lightweight, efficient, and automated approach to web testing and automation, making it a valuable
tool for software development and testing workflows.
15. What is serialization in java?
Serialization in Java is the concept of representing an object's state as a byte stream. The byte stream has all the information about the object.
Serialization in Java helps transport the code from one JVM to another and then de-serialize it there.
You can take any example as realtime such as that you are going to visit your home after 20 yrs and you want the same things,same
arrangements and many more things which you left 20 yrs ago in same condition as where u left.. then it is serialization.
16. What is Transient in Java?
In Java, the `transient` keyword is used to indicate that a variable should not be serialized when an object is converted into a stream of bytes,
typically for storage or transmission purposes. When an object is serialized, all of its non-transient instance variables are converted into a byte
stream, which can then be written to a file, sent over a network, or stored in a database. However, transient variables are excluded from this
process.
Here are some key points about the `transient` keyword:
1. Preventing Serialization: When a variable is marked as `transient`, its value is not included when the object is serialized. This can be useful for
variables that contain sensitive or unnecessary data that should not be persisted.
2. Default Values: Transient variables are assigned default values (e.g., `null` for object references, `0` for numeric types) during deserialization,
as they are not read from the byte stream.
3. Example Usage: Common use cases for the `transient` keyword include:
- Excluding transient fields that are not serializable (e.g., file handles, database connections).
- Excluding derived or calculated fields that can be re-computed during deserialization.
- Excluding sensitive data (e.g., passwords, authentication tokens) that should not be persisted.
4. Serialization Control: While marking a variable as `transient` prevents it from being serialized by default, you can customize the serialization
process by providing custom serialization methods (`writeObject` and `readObject`) in the class. These methods allow you to manually serialize
and deserialize transint variables if needed.
5. Thread Safety: The `transient` keyword does not affect the thread safety of a variable. It only controls whether the variable is included in the
serialization process.

17. What is Wrapper Class?


In Selenium, a wrapper class is a custom class built around the Selenium WebDriver API to simplify and enhance its functionality. It
encapsulates common Selenium actions and methods into more user-friendly and reusable functions, making test automation code more readable
and maintainable. Overall, wrapper classes in Selenium help in writing cleaner, more efficient, and maintainable test automation code by
providing a layer of abstraction on top of the WebDriver API.
In Java, a wrapper class is a class that encapsulates (wraps) primitive data types into objects. While primitive data types represent simple values
like integers, characters, or booleans, wrapper classes provide a way to treat these primitive types as objects. Each primitive type in Java has a
corresponding wrapper class, and these wrapper classes provide various utility methods and functionalities.
Here are the commonly used wrapper classes in Java:
1. Integer: Represents an integer value (`int`). Provides methods for converting integers to strings, parsing strings to integers, and performing
arithmetic operations.
2. Long: Represents a long integer value (`long`). Similar to the `Integer` class but for long integers.
3. Float: Represents a floating-point value (`float`). Provides methods for converting floats to strings, parsing strings to floats, and performing
arithmetic operations.
4. Double: Represents a double-precision floating-point value (`double`). Similar to the `Float` class but for double-precision floating-point
numbers.
5. Boolean: Represents a boolean value (`boolean`). Provides methods for converting booleans to strings and parsing strings to booleans.
6. Character: Represents a single character (`char`). Provides methods for converting characters to strings and performing character-related
operations.
7. Byte: Represents a byte value (`byte`). Similar to the other numeric wrapper classes but for bytes
8. Short: Represents a short integer value (`short`). Similar to the other numeric wrapper classes but for short integers.
Wrapper classes are often used in situations where objects are required, such as collections (e.g., `ArrayList`, `HashMap`) or when working with
methods that require objects instead of primitive types. They also provide methods for converting between primitive types and their
corresponding object types.
Wrapper classes also offer constants representing the maximum and minimum values for each primitive type, as well as methods for converting
strings to primitive types (`parseXxx()` methods) and for comparing wrapper objects (`compareTo()` method).
18. What Maven Does?
Maven is a build automation tool primarily used for Java projects. It simplifies the build process by providing a standard way to manage project
dependencies, compile source code, package artifacts, and execute tests. Here are some key features and functionalities of Maven:
1. Project Object Model (POM): Maven uses a declarative XML file called `pom.xml` (Project Object Model) to define project configuration,
dependencies, and build settings. The POM file serves as the blueprint for the project and contains information such as project coordinates,
dependencies, plugins, and build profiles.
2. Dependency Management: Maven manages project dependencies automatically by resolving them from repositories such as Maven Central or
custom repositories. Dependencies are declared in the POM file, and Maven downloads them transitively, ensuring that all required libraries are
available during the build process.
3. Build Lifecycle: Maven defines a set of standard build phases (e.g., `compile`, `test`, `package`, `install`, `deploy`) and associated goals that
are executed sequentially during the build process. Each phase represents a specific stage in the software development lifecycle, and Maven
plugins bind goals to these phases to perform various tasks such as compiling source code, running tests, generating documentation, and
packaging artifacts.
4. Convention over Configuration: Maven follows the principle of "convention over configuration," which means that it encourages
standardization and consistency by providing sensible defaults and conventions. For example, Maven uses predefined directory layouts
(`src/main/java`, `src/test/java`, `src/main/resources`, etc.) and naming conventions to organize project files and resources.
5. Plugin Ecosystem: Maven features a rich ecosystem of plugins that extend its functionality and provide additional capabilities for various
tasks such as code quality analysis, static code analysis, code coverage, code generation, and deployment. Plugins can be configured in the POM
file to customize the build process according to project requirements.
6. Dependency Scopes and Transitivity: Maven supports different dependency scopes (e.g., `compile`, `test`, `runtime`, `provided`) to control the
visibility and availability of dependencies at different stages of the build process. Maven also handles dependency transitivity automatically,
resolving and including transitive dependencies transitively.
Overall, Maven simplifies project management and build automation for Java projects by providing a standardized and extensible build system
that automates repetitive tasks and enforces best practices. It is widely used in the Java community and is supported by a large ecosystem of
libraries, frameworks, and tools.

19. What is desired Capabilities?


Desired capabilities are a set of key-value pairs that define the characteristics or behavior of a browser or a mobile device in Selenium
WebDriver or Appium automation tests. They are used to configure the execution environment for the browser or mobile application under test.
Here's how desired capabilities work in different contexts:
1. Selenium WebDriver:
- When working with Selenium WebDriver for web browser automation, desired capabilities are used to configure the browser instance
launched by the WebDriver.
- Desired capabilities include settings such as browser name, browser version, platform (OS), screen resolution, browser window size, proxy
settings, and more.
- Examples of desired capabilities for Selenium WebDriver include:
- `browserName`: Name of the browser to be used (e.g., "chrome", "firefox").
- `version`: Version of the browser.
- `platform`: Operating system platform to run the browser on (e.g., "WINDOWS", "MAC", "LINUX").
- `chromeOptions`: Additional options specific to the Chrome browser, such as preferences or extensions.
- Desired capabilities are passed as parameters when initializing the WebDriver instance.
2. Appium:
- In mobile automation using Appium, desired capabilities are used to configure the execution environment for mobile devices or emulators.
- Desired capabilities specify attributes such as device name, platform name, platform version, app package, app activity, automation name,
and more.
- Examples of desired capabilities for Appium include:
- `platformName`: Name of the mobile platform (e.g., "Android", "iOS").
- `deviceName`: Name of the device or emulator.
- `platformVersion`: Version of the mobile platform.
- `appPackage`: Package name of the mobile application to be tested.
- `appActivity`: Activity name of the main application activity.
- Similar to Selenium WebDriver, desired capabilities are provided as parameters when initializing the Appium driver instance.
By specifying desired capabilities, automation testers can customize the execution environment to match the requirements of the test scenario
and ensure consistent and reliable test execution across different browsers, devices, and platforms.

20. What are the challenges you faced while working on the last Automation framework?
Creating an automation framework typically involves several challenges, ranging from technical hurdles to organizational issues. Here are some
common challenges faced during the development of an automation framework:
1. Tool Selection: Choosing the right tools for the framework can be challenging. You need to consider factors like compatibility with the
existing infrastructure, ease of use, scalability, and support.
2. Framework Design: Designing a flexible and scalable framework architecture that accommodates various types of tests (e.g., unit tests,
integration tests, end-to-end tests) can be complex. It requires a good understanding of the application's architecture and testing requirements.
3. Maintainability: Ensuring that the framework is easy to maintain and update as the application evolves is crucial. This involves writing
modular and reusable code, implementing coding standards, and establishing clear documentation.
4. Integration with CI/CD Pipelines: Integrating the automation framework with continuous integration and continuous deployment (CI/CD)
pipelines can be challenging. You need to ensure seamless execution of tests within the pipeline and generate meaningful reports.
5. Test Data Management: Managing test data effectively, especially in complex scenarios involving multiple test cases and environments, can
be challenging. It requires developing strategies for data generation, cleanup, and isolation.
6. Cross-browser and Cross-platform Testing: Ensuring compatibility across different browsers and platforms adds complexity to the automation
framework. You need to consider variations in browser behavior, device resolutions, and operating systems.
7. Synchronization and Wait Strategies: Dealing with synchronization issues and implementing reliable wait strategies to handle dynamic
elements and asynchronous behavior in web applications can be challenging.
8. Handling Test Failures: Developing mechanisms to handle test failures gracefully and identify root causes accurately is essential for
maintaining the reliability of the automation framework.
9. Scalability and Performance: Ensuring that the automation framework can scale to accommodate a growing number of tests and maintain
acceptable performance levels during execution is crucial.
10. Skill Gap and Training: Bridging the skill gap among team members and providing adequate training on the automation framework and
related technologies can be a challenge, especially in teams with varying levels of expertise.
Addressing these challenges requires a combination of technical expertise, collaboration among team members, and a commitment to continuous
improvement throughout the development lifecycle.

21. Explain your framework used in last project

We were following the BDD framework where we had configured Maven, TestNG, Cucumber, and
Selenium in the project and scripting language as Java, and were following the POM design pattern
where we created the separate classes for each web page of the Applications under the single
package and all the page related things like locators and methods we were writing there and In
separate package, We had created the StepDefination class for each page and we had provide the
implementation of each cucumber step of the feature file.

We were writing the TCS under the feature file in a separate package for each module and their user
stories. we had also configured the Extent report for generating the reports and we were running our
TCs using TestNG.

On this project, we were following the sprint process where we had a sprint of 4 weeks, So whenever a
new sprint starts a set of tickets get assigned to everyone, SO whatever the tickets

Certainly! In our last project, we utilized a Behavior-Driven Development (BDD) automation framework configured with TestNG, Extent
Report, Selenium WebDriver, Java, Cucumber, and Maven. Let's delve into each component and how they contributed to the automation
framework:
1. Behavior-Driven Development (BDD):
BDD encourages collaboration among team members by defining test scenarios in a human-readable format using a domain-specific language
(DSL) like Gherkin syntax (Given-When-Then). This approach focuses on the behavior of the system rather than implementation details,
facilitating better communication between developers, testers, and stakeholders.
2. TestNG:
TestNG is a testing framework that provides various features such as annotations, assertions, parameterization, dependency management, and
parallel execution. It is well-suited for both unit and integration testing and offers enhanced functionalities compared to traditional testing
frameworks like JUnit.
3. Extent Report:
Extent Report is a comprehensive HTML reporting library that generates detailed and visually appealing test reports. It includes features like
logs, screenshots, charts, and historical data, making it easier to analyze test results and identify issues. Extent Report enhances the visibility and
understandability of test outcomes.
4. Selenium WebDriver:
Selenium WebDriver is a powerful tool for automating web browsers. It enables interaction with web elements, simulation of user actions
(e.g., clicks, typing), and verification of expected behaviors. Selenium WebDriver supports multiple browsers and platforms, making it suitable
for cross-browser testing.
5. Java:
Java is a widely-used programming language known for its platform independence, strong community support, and extensive ecosystem of
libraries and frameworks. In test automation, Java is commonly used due to its object-oriented nature, compatibility with Selenium WebDriver,
and availability of rich libraries for various tasks.
6. Cucumber:
Cucumber is a BDD tool that facilitates writing test scenarios in Gherkin syntax and executing them as automated tests. It promotes
collaboration by providing a common language for discussing and defining requirements. Cucumber maps Gherkin scenarios to corresponding
step definitions implemented in Java.
7. Maven:
Maven is a build automation tool that simplifies project management and dependency resolution. It manages project dependencies, compiles
source code, runs tests, and generates artifacts like JAR files. Maven's standardized project structure and lifecycle phases make it easy to manage
and maintain projects, especially in conjunction with popular testing frameworks like TestNG.
In our framework, Maven served as the build automation tool, managing project dependencies, compiling source code, and executing tests. We
utilized Cucumber for defining test scenarios in Gherkin syntax, TestNG for test execution and management, Selenium WebDriver for web
automation, Java for implementing step definitions and supporting code, and Extent Report for generating detailed test reports. This combination
facilitated behavior-driven test automation with robust reporting capabilities and streamlined project management.

22. what is public static void main(String[] args) explain in detail.


The `public static void main(String[] args)` method is the entry point of a Java program. When you run a Java application, the Java Virtual
Machine (JVM) starts executing the program by invoking this method.
1. public: This keyword specifies the access level of the method. In Java, `public` means that the method can be accessed from any other class.
2. static: This keyword indicates that the method belongs to the class itself, rather than to a specific instance of the class. As a result, you can
invoke the `main` method without creating an instance of the class.
3. void: This keyword specifies that the method does not return any value. The `main` method does not return anything because it is simply the
starting point of the program's execution.
4. main: This is the name of the method. By convention, it is called `main`, and it serves as the entry point of the program.
5. String[] args: This parameter represents an array of strings that can be passed as command-line arguments when running the program. The
`args` array contains any command-line arguments provided by the user when launching the application.

23. If we are calling a method in main method and you are getting null then what is the reason
If you're calling a method within the `main` method and encountering a `null` value, there are several potential reasons for this:
1. Null Object Reference: The method you're calling might be expecting an object reference as an argument, but you're passing `null` instead of a
valid object reference. This could happen if you haven't properly initialized the object or if the object reference is being set to `null` somewhere
in your code.
2. Null Return Value: The method you're calling might be returning `null`, indicating that it failed to produce a valid result. This could happen if
the method encounters an error condition or if it's designed to return `null` under certain circumstances.
3. NullPointerException: If you're trying to access a method or property of an object that is `null`, it will result in a `NullPointerException`. This
commonly occurs when you forget to initialize an object before using it, or if an object's reference is set to `null` at some point.
4. Incorrect Method Invocation: It's possible that you're calling the method with incorrect arguments or in an incorrect context, leading to
unexpected behavior or a `null` result.

24. what is try and catch?


In Java, the `try` and `catch` blocks are used together to handle exceptions, which are unexpected or abnormal conditions that occur during the
execution of a program.
1. try block:
- The `try` block encloses the code that might throw an exception.
- The `try` block must be followed by either a `catch` block, a `finally` block, or both.
2. catch block:
- A `catch` block is used to handle exceptions thrown by the code within the corresponding `try` block.
- It specifies the type of exception it can catch using the `catch` keyword followed by the exception type in parentheses.
- When an exception of the specified type occurs in the `try` block, control is transferred to the corresponding `catch` block.
- You can have multiple `catch` blocks to handle different types of exceptions.
- If an exception occurs that does not match any of the specified types in the `catch` blocks, it will propagate up the call stack until it's caught
or the program terminates.
3. finally block:
- A `finally` block is optional and follows the `try` and `catch` blocks.
- It is always executed, regardless of whether an exception occurred or not.
- It is commonly used to perform cleanup tasks, such as closing files or releasing resources, that should be executed regardless of whether an
exception occurred.

25. Which type of XPath do you use and why do you use relative XPath
In Selenium WebDriver, there are two main types of XPath expressions that can be used to locate elements on a web page:
1. Absolute XPath:
- Absolute XPath expressions start from the root node of the HTML document and specify the complete path to the desired element.
- They begin with a single forward slash (`/`) and navigate through each element in the document hierarchy until reaching the target element.
- Example: `/html/body/div[1]/div[2]/form/input[1]`
2. Relative XPath:
- Relative XPath expressions start from any element in the document and specify the path to the desired element relative to that context node.
- They don't necessarily begin with a forward slash and can navigate through elements using various axes and attributes.
- Example: `//input[@id='username']`
While both types of XPath expressions can be used to locate elements, relative XPath expressions are generally preferred for several reasons:
1. Robustness: Relative XPath expressions are less brittle than absolute XPath expressions because they are not dependent on the structure of the
entire document. They are more resilient to changes in the DOM hierarchy, such as adding or removing parent elements.
2. Readability: Relative XPath expressions are often more concise and readable than absolute XPath expressions. They focus on the relevant
attributes and relationships of elements, making it easier to understand their purpose.
3. Maintainability: Relative XPath expressions are easier to maintain over time because they are typically shorter and more targeted. When the
structure of the web page changes, it's often simpler to adjust a relative XPath expression to accommodate the changes.
4. Flexibility: Relative XPath expressions provide greater flexibility in locating elements based on their attributes, relationships, and context
within the document. They can leverage various axes, predicates, and functions to navigate through the DOM efficiently.
5. Performance: Relative XPath expressions can be more efficient in terms of performance because they focus on specific subsets of the
document rather than traversing the entire DOM hierarchy from the root node.
Overall, relative XPath expressions offer a more robust, readable, maintainable, flexible, and performant approach to locating elements on web
pages, making them the preferred choice for most Selenium WebDriver automation tasks.

26. What is 'this' and why we use this


In Java, `this` is a keyword that refers to the current instance of the class in which it appears. It can be used within instance methods or
constructors to refer to the current object.
`this` is a reference to the current object in Java, and it is commonly used to access instance variables, distinguish between local and instance
variables, pass the current object, perform constructor chaining, and enable method chaining.

1. Reference to Current Object:


- When a method or constructor is invoked on an object, `this` can be used to refer to that object itself.
- It allows you to access instance variables, call other methods, or pass the current object as an argument to other methods.
2. Distinguishing Between Local Variables and Instance Variables:
- When a method or constructor has a local variable with the same name as an instance variable, using `this` allows you to differentiate
between them.
- It helps clarify which variable you're referring to and avoids ambiguity in the code.
3. Passing the Current Object:
- You can use `this` to pass the current object as an argument to other methods or constructors.
- It's commonly used in method chaining or when initializing one object with another object's state.
4. Constructor Chaining:
- In constructors, `this` can be used to call another constructor in the same class.
- This is useful for constructor chaining, where one constructor initializes common attributes and then delegates to another constructor to
perform additional initialization.
5. Returning the Current Object:
- Methods can return `this` to allow method chaining, where multiple method calls can be chained together on the same object.
- It enhances readability and conciseness of code, especially when performing a series of operations on the same object.

27. What is API testing, and why do we do API testing?


API testing involves testing the Application Programming Interfaces (APIs) directly, focusing on their functionality, reliability, performance,
security, and compliance with specifications. APIs allow different software systems to communicate and interact with each other, enabling the
exchange of data and services between applications.
Here's why we do API testing and its significance:
1. Testing Application Logic: API testing verifies that the API endpoints behave as expected and perform the intended operations accurately.
2. Early Detection of Issues: API testing can be performed at an early stage of the software development lifecycle, even before the user interface
is fully developed. This enables the early detection and resolution of issues, reducing the overall cost and effort of fixing defects.
3. Isolation of Components: API testing allows you to isolate individual components or modules of an application and test them independently.
This facilitates more granular testing and enables thorough validation of each component's behaviour.
4. Automation-Friendly: APIs are inherently machine-readable and programmatically accessible, making them well-suited for automation. API
testing can be easily automated using testing frameworks and tools, allowing for faster and more efficient testing.
5. Improved Test Coverage: API testing complements other testing approaches, such as unit testing and end-to-end testing. It helps achieve
comprehensive test coverage by focusing on the functional aspects of the application at a higher level of abstraction.
6. Performance Testing: APIs play a critical role in determining the performance and scalability of an application. API testing allows you to
assess the performance of API endpoints under various conditions, such as different load levels, network latencies, and data volumes.
7. Security Testing: APIs are potential entry points for security threats and vulnerabilities. API testing helps identify security weaknesses, such
as improper authentication, authorization issues, data exposure, and injection attacks, enabling proactive security measures to be implemented.
8. Integration Testing: APIs facilitate integration between different components, systems, and third-party services. API testing ensures that these
integrations work seamlessly and reliably, preventing interoperability issues and data inconsistencies.
In summary, API testing is essential for verifying the functionality, reliability, performance, security, and compliance of APIs. It plays a crucial
role in ensuring the overall quality and robustness of software applications, facilitating early defect detection, automation, and comprehensive
test coverage.

28. What is postman and why we use Postman?


Postman is a popular API development and testing tool that simplifies the process of designing, testing, and debugging APIs. It provides a user-
friendly interface for creating and sending HTTP requests, inspecting responses, and collaborating with team members on API-related tasks.
1. API Testing: Postman allows testers to create and execute a wide range of API tests, including functional tests, regression tests, performance
tests, and security tests. It supports various request types, such as GET, POST, PUT, DELETE, PATCH, and OPTIONS, and provides features
for parameterization, data-driven testing, and test scripting.
2. Automated Testing: Postman enables the automation of API tests through collections and test scripts. Test scripts can be written in JavaScript
using the Postman Sandbox, allowing testers to perform complex assertions, extract data from responses, and automate workflows. Collections
can be exported and run using the Postman Collection Runner or integrated with continuous integration (CI) and continuous deployment (CD)
pipelines.
3. API Documentation: Postman provides tools for generating interactive API documentation from API requests and responses. Documentation
can be exported in various formats, such as HTML, Markdown, and JSON, and shared with stakeholders to facilitate understanding and usage of
the API.
4. Mock Servers: Postman allows testers to create mock servers to simulate API responses without the need for backend implementation. Mock
servers can be used for development, testing, and demo purposes, enabling frontend and backend teams to work independently and accelerate the
development process.
5. Monitoring and Debugging: Postman provides features for monitoring API performance, uptime, and response times. It allows testers to
debug API requests and responses using built-in tools for inspecting headers, payloads, and cookies, as well as viewing console logs and network
activity.
6. Collaboration and Sharing: Postman facilitates collaboration among team members by providing features for sharing collections,
environments, and documentation. It supports team workspaces, version control, and role-based access control (RBAC), allowing teams to work
together efficiently and securely on API-related tasks.
7. Integration with Third-Party Services: Postman integrates with various third-party services and tools, such as version control systems (e.g.,
GitHub, GitLab), CI/CD platforms (e.g., Jenkins, CircleCI), and API monitoring tools (e.g., New Relic, Datadog). These integrations enhance
the capabilities of Postman and streamline the API development and testing workflow.
Overall, Postman is widely used by developers, testers, and API stakeholders to streamline API development, testing, and collaboration, enabling
teams to build high-quality APIs more efficiently and effectively.

29. What is parameterization in API testing?


Parameterization in API testing refers to the practice of dynamically providing input values to API requests and validating the corresponding
output responses. It involves passing different sets of data to API requests during testing to evaluate the behavior of the API under various
scenarios. Parameterization allows you to test a wide range of input values, test cases, and edge cases without duplicating test scripts.
1. Input Parameters: In API testing, input parameters represent the data or values sent to the API endpoint as part of the request. These
parameters can include query parameters, headers, request body (e.g., JSON or XML payloads), and authentication credentials.
2. Test Data: Test data includes various combinations of input values that you want to test against the API. This data may come from different
sources, such as test databases, spreadsheets, CSV files, or generated programmatically.
3. Parameterization Techniques:
- Data-Driven Testing: In data-driven testing, you provide a dataset containing input values and expected outcomes. The test script iterates
over each set of input values, sends requests to the API with those values, and validates the responses against the expected outcomes.
- Randomized Testing: Randomized testing involves generating random input values within specified ranges or constraints. This technique
helps uncover unexpected behavior and edge cases that may not be covered by predefined test cases.
- Environment-Specific Testing: Parameterization allows you to test the API under different environments, such as development, testing,
staging, and production. You can customize input parameters (e.g., API endpoints, authentication tokens) based on the target environment.
- Boundary Value Analysis: Boundary value analysis involves testing input values at the boundaries of valid ranges, as well as just outside
those boundaries. This helps identify potential boundary-related issues, such as off-by-one errors and boundary conditions.
4. Automation: Parameterization is often implemented in automated API testing frameworks using scripting or programming languages such as
Python, Java, or JavaScript. Test scripts are designed to accept input parameters dynamically and execute test cases iteratively with different data
sets.
5. Validation: After sending API requests with parameterized input values, the corresponding responses are validated against expected outcomes.
Validation criteria may include response status codes, headers, body content, and performance metrics.
Benefits of parameterization in API testing include:
- Increased test coverage by testing multiple scenarios and edge cases.
- Reusability of test scripts across different input data sets.
- Enhanced flexibility and scalability in managing test data.
- Improved efficiency through automation and iteration over data sets.
- Early detection of issues and vulnerabilities in the API.
In summary, parameterization is a fundamental practice in API testing that enables thorough testing of API functionality, performance, and
reliability by dynamically varying input values and evaluating corresponding output responses.

30. What are the different error codes in API testing?


In API testing, error codes are status codes returned by the server in response to an API request. These codes indicate the outcome of the request
and provide information about the success or failure of the operation.
1. 200 OK:
- This status code indicates that the request was successful, and the server has returned the requested resource.
- It is the standard response for successful HTTP requests.
2. 201 Created:
- The server has successfully created a new resource as a result of the request.
- This status code is typically returned for POST requests that result in the creation of a new resource on the server.
3. 204 No Content:
- The server has successfully fulfilled the request, but there is no content to return.
- It is often used for operations that don't require a response body, such as DELETE requests.
4. 400 Bad Request:
- This status code indicates that the server cannot process the request due to a client error, such as invalid syntax or missing parameters.
- It is commonly used to indicate errors in the request payload or URL parameters.
5. 401 Unauthorized:
- The request requires user authentication, but the client has not provided valid credentials or the credentials are invalid.
- It is often used when the client needs to authenticate with the server using an API key, token, or username/password.
6. 403 Forbidden:
- The server understands the request, but the client is not allowed to access the requested resource.
- It may be returned if the client lacks the necessary permissions to perform the requested operation.
7. 404 Not Found:
- The server cannot find the requested resource or endpoint.
- It is commonly returned when the URL or endpoint specified in the request does not exist on the server.
8. 405 Method Not Allowed:
- The request method (GET, POST, PUT, DELETE, etc.) is not supported for the requested resource.
- It is often used when the client tries to use an unsupported HTTP method for a particular endpoint.
9. 500 Internal Server Error:
- This status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
- It is a generic error message returned when the server encounters an internal error, such as a bug or misconfiguration.
10. 503 Service Unavailable:
- The server is temporarily unable to handle the request due to maintenance or overload.
- It is often used when the server is undergoing maintenance, experiencing high traffic, or temporarily unavailable for some other reason.
These are just a few examples of common error codes encountered in API testing. It's essential to understand the meaning and implications of
different status codes to effectively test and troubleshoot APIs.

31. What is the difference between Request and response time?


The difference between request time and response time lies in their respective roles and the phases of communication between a client and a
server in a client-server model, such as in the context of HTTP communication:
1. Request Time:
- Request time refers to the time taken for a client to send a request to a server.
- It measures the duration from when the client initiates the request until the request is fully transmitted to the server.
- Request time includes factors such as establishing the connection with the server, sending the request headers and body (if any), and waiting
for the server to receive the complete request.
2. Response Time:
- Response time refers to the time taken for a server to process the request and send a response back to the client.
- It measures the duration from when the server receives the complete request until it sends the complete response back to the client.
- Response time includes factors such as processing the request, executing any necessary operations or computations, fetching data from
databases or external services, generating the response body, and transmitting the response back to the client.
In summary, request time measures the duration from when the client initiates the request until it is fully transmitted to the server, while
response time measures the duration from when the server receives the request until it sends the complete response back to the client. Together,
these two metrics provide insights into the performance and responsiveness of the client-server communication process.
32. Explain Test plan vs test strategy.
Test Plan and Test Strategy are two important documents in software testing that serve different purposes but are closely related to each other.
Let's explore each of them:
1. Test Plan:
- A Test Plan is a comprehensive document that outlines the approach, scope, resources, schedule, and deliverables for testing a particular
software product or system.
- It provides detailed information about the testing activities to be performed, including test objectives, test environment setup, test execution
schedule, test entry and exit criteria, test deliverables, and risk management.
- A Test Plan is typically created by the Test Manager or Test Lead in collaboration with other stakeholders, such as project managers,
developers, and business analysts.
- Key components of a Test Plan may include:
- Introduction and Overview
- Test Objectives
- Scope and Features to be Tested
- Test Strategies and Techniques
- Test Schedule and Milestones
- Test Environment Setup
- Test Deliverables
- Entry and Exit Criteria
- Risk Management
- Roles and Responsibilities
- Approval and Sign-off Process

2. Test Strategy:
- A Test Strategy is a high-level document that defines the overall approach, goals, and methods for testing a software product or system.
- It provides a framework for planning and executing testing activities throughout the software development lifecycle (SDLC), including unit
testing, integration testing, system testing, and acceptance testing.
- A Test Strategy outlines the testing objectives, test design techniques, test automation approach, defect management process, and other
aspects of testing that will be applied across the project.
- The Test Strategy is usually created early in the project lifecycle and serves as a reference guide for the entire testing effort.
- Key components of a Test Strategy may include:
- Introduction and Purpose
- Testing Objectives and Goals
- Scope and Coverage
- Test Levels and Types
- Testing Techniques and Approaches
- Test Automation Strategy
- Defect Management Process
- Test Environment and Infrastructure
- Roles and Responsibilities
- Metrics and Reporting
- Risks and Contingencies

In summary, while a Test Plan focuses on the detailed planning and execution of testing activities for a specific project or release, a Test Strategy
provides a broader framework and guidelines for testing across the organization or project. Both documents are essential for ensuring the
successful implementation of testing activities and achieving the desired quality goals for the software product or system.
33. What instance used for the safari browser
To automate Safari browser using Selenium WebDriver in Java, you need to use the SafariDriver class. However, please note that SafariDriver
requires additional setup steps compared to other browsers like Chrome or Firefox.
1. Download Safari Technology Preview:
- SafariDriver is not directly bundled with Selenium WebDriver. Instead, it's provided as part of Safari Technology Preview.
- Download and install Safari Technology Preview from the official Apple website: [Safari Technology
Preview](https://developer.apple.com/safari/technology-preview/)
2. Enable Developer Mode in Safari:
- Open Safari Technology Preview.
- Go to Safari > Preferences > Advanced.
- Check the "Show Develop menu in menu bar" option.
3. Enable Remote Automation in Safari:
- Go to Develop > Allow Remote Automation.
4. Set System Property for SafariDriver:
- Before creating an instance of SafariDriver, you need to set the `webdriver.safari.driver` system property to the location of the SafariDriver
executable.
- The SafariDriver executable is typically located at `/usr/bin/safaridriver` on macOS.
Keep in mind that SafariDriver has some limitations and may not support all features or work as smoothly as other browser drivers. Additionally,
SafariDriver is only available on macOS. If you're automating tests for multiple platforms, you may need to use a different browser or approach
for cross-platform compatibility.

34. What is Page factory ?


Page Factory is a design pattern in Selenium WebDriver that provides an efficient way to initialize and manage web elements in Page Objects. It
aims to enhance the readability, maintainability, and reusability of test automation code by encapsulating the initialization of web elements
within the page objects themselves. Page Factory is part of the Page Object Model (POM) approach, where each web page in an application is
represented by a corresponding Page Object.
Here's how Page Factory works and why it's useful:
1. Initialization of Web Elements:
- In traditional Selenium WebDriver scripts, web elements are typically initialized using `findElement()` or `findElements()` methods directly
within test scripts or page objects.
- With Page Factory, the initialization of web elements is abstracted away from the test scripts and encapsulated within the Page Object class.
- Page Factory provides annotations such as `@FindBy`, `@FindAll`, and `@FindBys` to declare web elements in Page Object classes.
2. Annotations for Locating Web Elements:
- Annotations provided by Page Factory, such as `@FindBy`, allow you to declare web elements using various locators (e.g., ID, name, CSS
selector, XPath) directly within the Page Object class.
- This approach makes the code more readable and reduces redundancy by centralizing the declaration of web elements in one place.
3. Lazy Initialization:
- Page Factory initializes web elements lazily, meaning that elements are not initialized until they are accessed by test scripts.
- This lazy initialization helps improve performance by avoiding unnecessary calls to `findElement()` or `findElements()` for web elements
that are not used in the current test scenario.
4. Automatic Initialization using initElements():
- Page Factory provides a utility method called `initElements()` to initialize web elements declared using annotations in Page Object classes.
- You can call `initElements()` in the constructor of the Page Object class to automatically initialize all annotated web elements.

35. Use of @findby annotations


The `@FindBy` annotation in Selenium WebDriver is used to declare web elements within Page Object classes. It helps in locating and
initializing web elements using various locators such as ID, name, CSS selector, XPath, etc. The `@FindBy` annotation is part of the Page
Factory pattern, which provides a convenient way to manage Page Objects and their associated web elements.

Here's how the `@FindBy` annotation is used and its significance:


1. Declaration of Web Elements:
- You can declare web elements directly within Page Object classes using the `@FindBy` annotation.
- The `@FindBy` annotation is applied to instance variables representing web elements.
2. Locating Web Elements:
- The `@FindBy` annotation allows you to specify locators for web elements using different strategies, such as ID, name, CSS selector, XPath,
class name, link text, or partial link text.
- You can specify the locator strategy and the value of the locator using attributes of the `@FindBy` annotation.
3. Initialization of Web Elements:
- When the `PageFactory.initElements()` method is called in the constructor of the Page Object class, web elements declared with `@FindBy`
annotations are initialized.
- The WebDriver instance passed to `initElements()` is used to locate and initialize the web elements based on the specified locators.
4. Lazy Initialization:
- Web elements declared with `@FindBy` annotations are initialized lazily, meaning that they are not initialized until they are accessed by test
scripts.
- This lazy initialization approach improves performance by avoiding unnecessary calls to locate web elements that are not used in the current
test scenario.

36. What kind of API is used in Postman?


Postman primarily utilizes RESTful APIs for interacting with web services. REST (Representational State Transfer) is an architectural style for
designing networked applications, commonly used for building APIs on the web. RESTful APIs adhere to REST principles and use HTTP
methods (GET, POST, PUT, DELETE, etc.) to perform CRUD (Create, Read, Update, Delete) operations on resources.
Here's how Postman uses RESTful APIs
1. HTTP Requests:
- Postman allows users to create and send various types of HTTP requests, including GET, POST, PUT, DELETE, PATCH, OPTIONS, and
more.
- Users can specify request parameters, headers, body content (e.g., JSON, XML), and authentication details for each request.
2. Response Handling:
- Postman captures and displays the responses received from the server after sending requests.
- Users can inspect response headers, body content, status codes, and cookies to validate API behavior and troubleshoot issues.
3. Collections and Environments:
- Postman enables users to organize and manage API requests into collections, which can be shared and reused across team members.
- Users can define environments to parameterize requests and manage variables (e.g., base URLs, authentication tokens) for different testing or
production environments.
4. Test Automation:
- Postman provides features for writing and executing test scripts to automate API testing.
- Test scripts can be written in JavaScript using Postman's scripting sandbox, allowing users to perform assertions, data manipulation, and
workflow automation.
5. Mock Servers:
- Postman allows users to create mock servers to simulate API responses without the need for a backend implementation.
- Mock servers can be used for development, testing, and demo purposes, enabling frontend and backend teams to work independently.
6. API Documentation:
- Postman provides tools for generating interactive API documentation from API requests and responses.
- Users can export documentation in various formats (e.g., HTML, Markdown, JSON) and share it with stakeholders to facilitate understanding
and usage of the API.
Overall, Postman is a versatile tool for working with RESTful APIs, offering a comprehensive set of features for designing, testing, debugging,
and documenting APIs throughout the software development lifecycle.

37. What are the errors you know in the postman?


In Postman, errors can occur due to various reasons, ranging from issues with the request configuration to problems with the server's response.
Here are some common errors you may encounter while using Postman:
1. Request Errors:
- Invalid URL: The URL specified in the request is malformed or incorrect.
- Missing Headers: Required headers are missing or incorrectly formatted in the request.
- Invalid Parameters: Request parameters are missing or have invalid values.
- Authentication Errors: Authentication credentials (e.g., API key, OAuth token) provided in the request are invalid or expired.
2. Connection Errors:
- Connection Timeout: The server does not respond within the specified timeout period.
- Network Error: There are network connectivity issues preventing the request from reaching the server.
3. Response Errors:
- HTTP Status Codes: The server returns an HTTP status code indicating an error, such as 4xx (client error) or 5xx (server error).
- Invalid Response Format: The server returns a response in an unexpected or invalid format (e.g., non-JSON response for an API expecting
JSON).
- Empty Response: The server returns an empty response or no response at all.
4. Authorization Errors:
- Unauthorized: The server returns a 401 Unauthorized status code, indicating that the request lacks valid authentication credentials.
- Forbidden: The server returns a 403 Forbidden status code, indicating that the request is not allowed due to insufficient permissions.
5. Server-Side Errors:
- Internal Server Error: The server encounters an unexpected condition that prevents it from fulfilling the request, resulting in a 500 Internal
Server Error status code.
- Service Unavailable: The server is temporarily unable to handle the request, usually due to maintenance or overload, resulting in a 503
Service Unavailable status code.
6. SSL Certificate Errors:
- SSL Handshake Error: There are issues with SSL/TLS handshake, such as expired or invalid SSL certificates.
- SSL Certificate Verification Failed: Postman fails to verify the server's SSL certificate, usually due to self-signed certificates or certificate
chain issues.
7. Scripting Errors:
- Test Script Errors: Errors occur in the JavaScript test scripts written to validate the response or perform additional processing.
- Pre-request Script Errors: Errors occur in the JavaScript pre-request scripts used to modify the request before it is sent.
These are just some of the common errors you may encounter while using Postman. When troubleshooting errors, it's essential to carefully
review the request configuration, server response, and any associated error messages to identify and resolve the underlying issues.

38. How to implement automation with Jira?


Implementing automation with Jira involves integrating automated testing processes with Jira's issue tracking and project management
capabilities. This integration helps streamline development workflows, improve collaboration, and ensure that issues are promptly identified,
tracked, and resolved. Here's a general outline of how to implement automation with Jira:
1. Select Test Automation Tools: Choose test automation tools and frameworks that integrate seamlessly with Jira. Popular options include
Selenium WebDriver for web application testing, Appium for mobile application testing, JUnit or TestNG for Java-based test automation, and
Cucumber for behavior-driven development (BDD) testing.
2. Set Up Test Automation Environment: Set up your test automation environment, including configuring test frameworks, setting up test scripts,
and ensuring that necessary dependencies (e.g., WebDriver binaries, test data) are in place.
3. Define Test Cases and Scenarios: Define test cases and scenarios that align with project requirements, user stories, and acceptance criteria.
Test cases should be well-documented and cover various functional and non-functional aspects of the application.
4. Integrate Test Automation with Jira:
- Install and configure Jira plugins or integrations that enable seamless integration with test automation tools. Some popular plugins include
Zephyr for Jira, Xray Test Management for Jira, and TestRail.
- Use Jira's REST API to programmatically create, update, and retrieve issues, test cases, and test execution results. This allows you to
automate interactions with Jira from your test scripts or automation frameworks.
5. Link Test Cases to Jira Issues: Link test cases and automated test scripts to corresponding Jira issues (e.g., user stories, tasks, bugs) to
establish traceability and ensure that testing efforts are aligned with project requirements.
6. Execute Automated Tests: Execute automated tests as part of your continuous integration (CI) and continuous deployment (CD) pipelines.
Integrate test automation with build servers (e.g., Jenkins, Bamboo) to trigger automated tests automatically upon code commits or deployments.
7. Capture Test Execution Results: Capture test execution results, including pass/fail status, screenshots, logs, and other relevant information.
Report test results back to Jira by updating corresponding test cases or issues with test execution details.
8. Monitor and Analyze Test Results: Monitor test execution progress and analyze test results to identify trends, patterns, and areas for
improvement. Use Jira dashboards, reports, and custom queries to track testing metrics and project health.
9. Automate Defect Reporting and Management: Automate defect reporting and management by automatically creating Jira issues (e.g., bugs,
tasks) for failed test cases and linking them to corresponding test execution results. Use Jira workflows and automation rules to streamline defect
triage and resolution processes.
10. Continuous Improvement: Continuously refine and improve your test automation strategy based on feedback, lessons learned, and evolving
project requirements. Regularly review and update test cases, test scripts, and automation frameworks to ensure their effectiveness and
maintainability.
By following these steps, you can effectively implement automation with Jira and leverage the power of automation to enhance the quality,
efficiency, and agility of your software development and testing processes.

39. What is Scrum?


- Scrum is an Agile framework for developing, delivering, and sustaining complex products. It emphasizes collaboration, iterative
development, and continuous improvement.
- In Scrum, work is organized into fixed-length iterations called sprints, typically lasting two to four weeks, during which a potentially
shippable product increment is produced.
- Scrum roles include the Scrum Master, Product Owner, and Development Team, each with specific responsibilities to ensure the success of
the Scrum process.

40. What is Agile?


- Agile is an iterative and incremental approach to software development that emphasizes flexibility, collaboration, and customer feedback.
- Agile methodologies prioritize delivering working software in small, frequent increments, enabling teams to respond to change quickly and
deliver value to customers faster.
- Agile principles are outlined in the Agile Manifesto, which values individuals and interactions, working software, customer collaboration,
and responding to change over following a rigid plan or process.

41. What is 3 amigos in Agile?


- The "Three Amigos" is a collaborative meeting in Agile software development involving three key roles: the Business Analyst (representing
business requirements), the Developer (representing technical implementation), and the Tester (representing testing scenarios).
- The purpose of the Three Amigos meeting is to ensure a shared understanding of user stories or requirements before development begins. The
three perspectives help identify potential issues, clarify ambiguities, and define acceptance criteria for user stories.

42. Who divides scrum into small units of sprint Duration?


- The Scrum Team collectively divides the work into small units of sprint duration during the Sprint Planning meeting. The Scrum Team
includes the Product Owner, Scrum Master, and Development Team members.
- Sprint duration is typically determined by the Scrum Team based on factors such as the project's complexity, team velocity, and
organizational context.

43. Who is the Product Owner?


- The Product Owner is a key role in Scrum responsible for representing the interests of stakeholders and maximizing the value delivered by
the Scrum Team.
- The Product Owner is responsible for defining the product vision, prioritizing the product backlog, and ensuring that the development team
understands the requirements and goals of each sprint.

44. Sprint Planning Meeting?


- The Sprint Planning meeting is a collaborative event in Scrum where the Scrum Team plans the work to be done during the upcoming sprint.
- During Sprint Planning, the Product Owner presents the prioritized product backlog items, and the Development Team discusses and selects
the items they believe they can complete in the sprint.
- The output of Sprint Planning is the sprint backlog, which contains the tasks necessary to deliver the selected product backlog items.

45. Daily Meeting vs Three Amigos Meeting?


- The Daily Standup Meeting (or Daily Scrum) is a short, time-boxed meeting held every day during the sprint where the Development Team
members synchronize their activities, discuss progress, and identify any obstacles or impediments.
- The Three Amigos Meeting, on the other hand, is a collaborative meeting involving the Business Analyst, Developer, and Tester to ensure a
shared understanding of user stories or requirements before development begins.
- While the Daily Standup focuses on the progress and coordination of development activities within the Development Team, the Three
Amigos Meeting focuses on ensuring a shared understanding of requirements among key stakeholders before development starts.

46. Which is the latest stable Verison you used in the automation project for Java, Maven, cucumber, and testNG?
1. Java: Java 11 was a commonly used stable version for automation projects, as it was a Long-Term Support (LTS) release with stability and
security updates.
2. Maven: Maven 3.6.x was a stable version widely used for managing project dependencies, building, and packaging Java projects. Maven 3.6.3
was a popular choice at the time.
3. Cucumber: Cucumber for Java was often used for behavior-driven development (BDD) testing. Version 6.10.4 was one of the stable releases
commonly used for Java-based automation projects.
4. TestNG: TestNG 7.x was widely used as a testing framework for Java projects. TestNG 7.4.0 was one of the stable releases available at the
time, offering various features for test execution, parallel testing, and reporting.

47. What is Get, post, put, delete, patch methods with examples?
HTTP methods (also known as HTTP verbs) are actions that indicate the desired operation to be performed on a resource.
1. GET:
- The GET method is used to request data from a specified resource.
- It should only retrieve data and should have no other effect on the server.
2. POST:
- The POST method is used to submit data to be processed to a specified resource.
- It can create a new resource or update existing resources.
3. PUT:
- The PUT method is used to update a specified resource with the provided data.
- It replaces the entire resource with the new data.
4. DELETE:
- The DELETE method is used to delete a specified resource.
- It removes the resource from the server.
5. PATCH:
- The PATCH method is used to apply partial modifications to a resource.
- It is typically used to update specific fields of an existing resource.
These HTTP methods allow clients to interact with web servers and perform various operations on resources according to the principles of the
RESTful architectural style.
48. Switch and SwitchHandlers:
- In automation, "Switch" typically refers to switching between different windows or frames in a web application. It's commonly used in
Selenium WebDriver to interact with multiple browser windows or iframes.
- "SwitchHandlers" might refer to the mechanisms or methods provided by Selenium WebDriver to perform window or frame switching.
Examples include `driver.switchTo().window()` for switching between browser windows and `driver.switchTo().frame()` for switching to
iframes.

49. HashMap vs HashTable:


- Both HashMap and HashTable are data structures in Java that store key-value pairs.
- HashMap is not synchronized, allowing better performance in single-threaded applications, but it's not thread-safe. HashTable is
synchronized and thread-safe.
- HashMap allows one null key and multiple null values. HashTable doesn't allow null keys or values.
- HashMap is generally preferred for new code due to better performance, while HashTable is used in legacy code or situations requiring
thread safety.

50. Native vs Hybrid App:


- A native app is built specifically for a particular platform (e.g., iOS or Android) using platform-specific programming languages and tools
(e.g., Swift/Objective-C for iOS, Java/Kotlin for Android).
- A hybrid app is built using web technologies (HTML, CSS, JavaScript) and wrapped in a native container that allows it to run on multiple
platforms. Hybrid apps often use frameworks like Apache Cordova or Ionic.

51. How to Execute Different Automation Scripts in Selenium:


- Automation scripts in Selenium can be executed using various test frameworks like TestNG or JUnit.
- You can create separate test classes for different scenarios or functionalities and organize them into test suites.
- Use build automation tools like Maven or Gradle to manage dependencies, compile, and execute test classes.
- Configure test execution environments (e.g., browsers, operating systems) using WebDriver and desired capabilities.

52. Listeners Annotation in Selenium:


- Listeners in Selenium are interfaces that listen to events generated by WebDriver during test execution.
- Annotations like `@BeforeTest`, `@AfterTest`, `@BeforeMethod`, and `@AfterMethod` can be used to define listener methods that execute
before or after test methods or test runs.
- Listeners are used for tasks like logging, capturing screenshots, or handling test failures.

53. Data-driven Testing vs Test-driven Testing:


- Data-driven testing involves executing tests with different sets of input data to validate the behavior of the system under test. Data is typically
stored in external sources like Excel sheets or databases.
- Test-driven testing involves writing test cases before implementing the corresponding functionality. It follows the "write test first, write code
later" approach advocated by test-driven development (TDD).

54. How to Execute Tests in Parallel:


- TestNG and JUnit support parallel execution of tests out-of-the-box.
- You can configure parallelism at the suite, test, or method level using annotations or XML configuration.
- Use Selenium Grid to distribute tests across multiple nodes (browsers and operating systems) for parallel execution.

55. What is XPath and its Types:


- XPath (XML Path Language) is a query language used to navigate XML and HTML documents to locate elements based on their attributes
and structure.
- Absolute XPath starts with the root node and includes the complete path to the desired element. Relative XPath starts from a specific node
and uses navigational steps to locate the element.

56. GIT Commands:


- Git is a version control system used to manage source code and collaborate on software development projects.
- Common Git commands include `git init` (initialize a new Git repository), `git clone` (clone a remote repository), `git add` (add changes to
the staging area), `git commit` (commit changes to the local repository), `git push` (push changes to a remote repository), `git pull` (fetch and
merge changes from a remote repository), and `git branch` (manage branches).

57. Simulator vs Emulator:


- A simulator mimics the behavior of a real device but runs on a different architecture or platform. It's typically faster than an emulator but may
not provide a completely accurate representation of the actual device.
- An emulator replicates the software and hardware environment of a real device, allowing applications to be tested in a realistic environment.
Emulators are slower but offer more accurate testing compared to simulators.
58. Method Overloading and Method Overriding:
- Method overloading involves defining multiple methods in the same class with the same name but different parameter lists. The methods can
have different numbers or types of parameters.
- Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The
method signature (name and parameter list) must be the same in both classes.

59. Selenium 4 Vs Selenium 3:


- Selenium 4 is the latest major version of Selenium WebDriver, introducing new features, improvements, and enhancements over Selenium 3.
- Some key features of Selenium 4 include improved relative locators, native support for the W3C WebDriver protocol, better support for
mobile testing, and a new Selenium Grid interface.
60. What is Class:
In object-oriented programming (OOP), a class is a blueprint for creating objects. It defines the attributes (fields) and behaviours (methods) that
objects of that class will have. Think of a class as a template or a prototype for objects.
Here's a breakdown of the key components of a class:
1. Attributes: Also known as fields or properties, attributes represent the data associated with objects of the class. They define the state of the
object. For example, a `Car` class might have attributes such as `make`, `model`, `year`, and `color`.
2. Methods: Methods are functions or procedures associated with a class that define its behavior. They represent the actions that objects of the
class can perform. For example, a `Car` class might have methods such as `start()`, `accelerate()`, `brake()`, and `turn()`, which define how a car
behaves.
3. Constructor: A constructor is a special method used for initializing objects of the class. It has the same name as the class and is invoked
automatically when an object is created. Constructors initialize the state of the object by assigning initial values to its attributes.
4. Encapsulation: Encapsulation is the principle of bundling the data (attributes) and methods that operate on the data into a single unit, i.e., the
class. It allows for better control over access to the data and helps in hiding the internal implementation details of the class from outside code.
5. Inheritance: Inheritance is a mechanism where a class (subclass or derived class) can inherit attributes and methods from another class
(superclass or base class). It promotes code reusability and allows for the creation of hierarchical relationships between classes.
6. Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables methods to
behave differently based on the object they are called on, leading to flexibility and extensibility in code design.

Introduction
1. 1st project: Guidewire
In my first project, I worked on manual things, because All the requirements were related to manual
things, So I was responsible for understanding the requirements and writing the Test cases and
executing them, So majorly I worked on manual testing on that project where I performed testing like
functional testing, exploratory testing, end to end testing, configuration testing regression testing and on
this project I also get chance to work on Integration testing of different guiderwire modules like PE, BE,
CC for their integration using Postman and SoupUI.
2. 2nd Project :
On my second project which was in the HealthCare domain, So i was given an opportunity to work on
automation where we converted the manual TCS into automation TCS using Java, Selenium and TestNG.
My responsibility was to convert the manual TCs into the automation TCs.

3. 3rd Project:
My 3rd project is in the Banking Domain, where I precisely worked on automation where I was enhancing
the framework and automating the TCS for business-critical scenarios, On this project, we were following
the BDD framework where we configured tools like Cucumber, Selenium, TestNG and scripting language
as Java, and now the automation is completed and scripts are in the maintenance phase and we
delivered the project So I am exploring one of the domains which are Supply Chain Management.

Apart from that I also having the experience with QA methodologies, analysing the requirements and also experience in writing and executing
the test cases with the intent of finding the bug.
also having the experience in creating and handling the defects throughout its entire life cycle from Creation to close using tools like Jira, Azure
DevOps.
Apart from this I have Good Knowledge in Software Development Life Cycle (SDLC) and I have worked on Agile Model where we were
following sprints process.
While working in the sprint I was involved in Sprint meetings, like Sprint Planning, Sprint demo, retrospective, Daily Scrum, etc.
That’s all from my Side, thank you.

We were following the BDD framework where we had configured Maven, TestNG, Cucumber, and
Selenium in the project and scripting language as Java, and were following the POM design pattern where
we created the separate classes for each web page of the Applications under the single package and all
the page related things like locators and methods we were writing there and In separate package, We
had created the StepDefination class for each page and we had provide the implementation of each
cucumber step of the feature file.

We were writing the TCS under the feature file in a separate package for each module and their user
stories. we had also configured the Extent report for generating the reports and we were running our TCs
using TestNG.

On this project, we were following the sprint process where we had a sprint of 4 weeks, So whenever a
new sprint starts a set of tickets get assigned to everyone, SO whatever the tickets

61. What is difference between Selenium 3 and 4:


Selenium 3: It primarily relied on the Selenium WebDriver API, which had some limitations and inconsistencies across different browsers.
Selenium 4: It adopts the WebDriver W3C Standard, which provides more consistency in interactions with web elements across browsers. This
improves cross-browser testing.
Selenium 3: Limited support for event listeners.
Selenium 4: Offers more comprehensive support for listening to browser events, making it easier to track user interactions and events like page
load, clicks, and more.
Selenium 3: Required manual updates for browser drivers.
Selenium 4: Offers automatic browser driver updates, reducing maintenance efforts.
62. What is the ThreadPool in TestNG?
Thread pool is a software design pattern for achieving concurrency of execution in a computer program.
In TestNG, the @Test(threadPoolSize=x) annotation defines the number of threads to be used while running a test method. It instructs TestNG
to construct a thread pool to run the test procedure in several threads. The test method's running time will be considerably reduced by using a
thread pool.
10 is the maxPoolSize - JVM can create max 10 threads.

63. How to perform Parallel testing?


64. How do you achieve parallel testing in TestNG?
TestNG allows running the tests in parallel by setting the “parallel” attribute in the “<suite>” tag respectively to “tests”, “methods”, “classes”,
“instances”. As per the setting provided to run the tests, it will start executing the tests in separate threads.

65. what is the major challenges in parallel testing


Inter-dependent Tests. When a test relies on the completion of another test, you can not run parallel tests. ...
Data Dependencies. Parallel testing can become challenging or impossible when multiple tests need access to the same data.

You might also like