Core Java Interview Questions and Answers by Advanto
Core Java Interview Questions and Answers by Advanto
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.
get A(){
}
set A(int a){
if(a>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.
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.
Example:
public class Manipulation{ //Super class
public void add(){
………………
}
}
}
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.
Size should be given at the time of array declaration. Size may not be required. It changes the size dynamically.
`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.
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.
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.
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
Inserted elements are in random order Maintains the elements in the sorted order
b) Vector:
It is the same as Array List.
Example:
public class Fruit {
public static void main (String [ ] args){
Vector <String> names = new Vector <String> ( );
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 <String> names = new linkedlist <String> ( ) ;
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]
Example:
public class Fruit {
public static void main (String[ ] args){
HashSet<String> names = new HashSet <=String>( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}
Output:
[banana, cherry, kiwi, apple]
Example:
public class Fruit {
public static void main (String[ ] args){
LinkedHashSet<String>; names = new LinkedHashSet <String>( ) ;
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<String> names= new TreeSet<String>( ) ;
names.add(“cherry”);
names.add(“banana”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“cherry”);
System.out.println(names);
}
}
Output:
[apple, banana, cherry, kiwi]
Example:
Public class Fruit{
Public static void main(String[ ] args){
HashMap<Sting,String> names =new HashMap<String,String>( );
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<Sting,String> names =new Hashtable<String,String>( );
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}
Example:
public class Fruit{
public static void main(String[ ] args){
LinkedHashMap<Sting,String> names =new LinkedHashMap<String,String>( );
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<Sting,String> names =new TreeMap<String,String>( );
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}
Checked Exceptions must either declare the exception using throws keyword (or) surrounded by appropriate try/catch.
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
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.
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();
}
}
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!
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.
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.
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.
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.
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.
A local variable is a variable that we declare inside a Method. A method will often store its temporary state in local
variables.
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.
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
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.
Syntax:
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
package softwareTestingMaterial;
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;
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;
34. Write a program to print the pattern given below (Pyramid Star Pattern)
*
**
***
****
*****
Here is the program to print the pattern mentioned above
}
Another method:
package softwareTestingMaterial;
}
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 {
int[] arr={28,3,15,9,17,4,23,2};
int val=arr[0];
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;
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;
import java.util.Scanner;
package softwareTestingMaterial;
package softwareTestingMaterial;
import java.util.Scanner;
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
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;
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;
ArrayList is an ordered collection and maintains insertion order HashSet is an unordered collection and doesn’t maintain
of elements insertion order
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.
protected: The scope of protected access modifier is within a package and also outside the package through inheritance
only.
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.
To know more about this you have to go through Method Overloading and Method Overriding.
To declare Abstract class we have to use abstract keyword To declare Interface we have to use interface keyword
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
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
meaning of webdriver driver = new Chromedriver(); where, Webdriver is Interface, driver is reference variable, New is keyword to create
variable and Chromedriver is construtor.
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
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.
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.
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.
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.
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.
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.
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.
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.
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