Most Asked JAVA and Selenium Questions
Most Asked JAVA and Selenium Questions
So if you have strong fundamentals in Java with good understanding and practice of Selenium, there is
no stopping for you. So here you go!
• A class loader is a Java object that loads Java classes into the Java Virtual Machine (JVM). Class
loaders are responsible for finding and loading class files into the JVM's memory space. They also verify
the integrity of the class files and ensure that they are compatible with the JVM.
• Bootstrap class loaders: Bootstrap class loaders are responsible for loading the core Java
classes that are necessary for the JVM to function.
• Extension class loaders: Extension class loaders are responsible for loading classes from the
Java extension library.
• System class loaders: System class loaders are responsible for loading classes from the user's
classpath.
• Class loaders are an important part of the Java runtime environment. They allow the JVM to
load classes on demand, which improves performance and reduces memory usage.
• Yes, it is possible to save a Java file without a name. However, this will only work if the file does
not contain any public classes. If the file does contain a public class, then you will need to give the class a
name.
3. What are wrapper classes and why do we need? Difference between int and Integer?
• Wrapper classes are Java classes that allow a value of a primitive type to be "wrapped up" into
an object. Wrapper classes often provide useful methods for manipulating the associated type.
• In Java, int is a primitive data type that can store the binary value of an integer. Integer is a
wrapper class for int that gives more flexibility in storing, converting, and manipulating int data.
• Integer can convert int into an object and vice versa.
• Integer consumes slightly more memory than int. int needs 4 bytes in Java, but Integer
occupies 16 bytes of memory.
4. What are immutable classes? Name 5 immutable classes in Java? How to make a class
immutable?
• Immutable classes are classes that cannot be changed after they have been created. This
means that once the values of the class's fields have been set, they cannot be changed. Immutable
classes are useful for many reasons, including:
• String
• Enum classes
• By following these steps, you can create a class that is immutable and thread-safe.
• Use final fields whenever possible. This will help to ensure that the values of the fields cannot
be changed after they have been set.
• Avoid using mutable objects as fields. If you must use a mutable object as a field, make sure
that it is wrapped in an immutable object.
• Use immutable builders when creating objects. This will help to ensure that the objects are
created in a consistent state.
• Test your immutable classes thoroughly. This will help to ensure that they are working as
expected
5. What are OOPS concepts? Explain them. What all OOPS concepts have you used in your
framework?
• Link: https://www.softwaretestingmaterial.com/oops-concept-in-automation-framework/
6. What is Object class in Java? Explain role and importance of toString, equal and hashcode
method?
The Object class is the root class of all classes in Java. Every Java class is directly or indirectly derived
from the Object class. The Object class contains methods that are common to all Java objects, such as
toString(), equals(), and hashCode().
The toString() method returns a string representation of the object. This method is often used to display
the contents of an object in a human-readable format. The equals() method compares two objects for
equality. The hashCode() method returns a hash code for the object. This hash code can be used to
quickly compare objects for equality.
The toString(), equals(), and hashCode() methods are important for many purposes, including:
The toString() method can be used to display the contents of an object in a way that is easy for humans
to understand. For example, the toString() method can be used to display the properties of a JavaBean
object.
The equals() method can be used to compare two objects for equality. For example, the equals() method
can be used to determine if two JavaBeans objects have the same properties.
• Hash tables:
A hash table is a data structure that uses a hash code to store and retrieve objects. The hashCode()
method can be used to calculate the hash code for an object. This hash code can then be used to quickly
look up an object in the hash table.
The Object class and its methods are essential components of the Java programming language. The
toString(), equals(), and hashCode() methods are used for a variety of purposes, including displaying
objects in a human-readable format, comparing objects for equality, and storing objects in hash tables.
• toString() method:
The toString() method returns a string representation of the object. The default implementation of
toString() simply returns the name of the class followed by the object's hash code. However, subclasses
can override this method to provide a more informative string representation of the object.
• equals() method:
The equals() method compares two objects for equality. The default implementation of equals() simply
checks if the two objects are the same instance. However, subclasses can override this method to
provide a more sophisticated definition of equality.
• hashCode() method:
The hashCode() method returns a hash code for the object. The default implementation of hashCode()
simplesmente returns the object's memory address. However, subclasses can override this method to
provide a more sophisticated definition of the hash code.
The Object class and its methods are powerful tools that can be used to improve the readability,
maintainability, and performance of Java code.
7. What is method overloading and overriding? What is upcasting and down casting?
• Upcasting and downcasting in Java are the two forms of typecasting. The purpose of
typecasting is to enable a function in a program to process the variables correctly. Upcasting refers to
typecasting a child object to a parent object. Downcasting provides casting a parent object to a child
object.
• In method overloading, you can define multiple methods with the same name but different
parameters within the same class.
• Method overloading is a type of static polymorphism. It helps to increase the readability of the
program.
• The access modifier must be either the same or a less restrictive one.
• Thrown checked exceptions, if any, can be removed or reduced by the overriding method.
8. Can we overload private and final methods? Can we override static methods?
Private methods are only accessible within the class они defined in, so they cannot be overloaded.
Final methods cannot be overridden, so they also cannot be overloaded.
Static methods are bound at compile time, so they are not virtual. This means that they can be
overloaded without causing an error.
Overloaded static methods have different signatures, which means that they have different names or
different parameters.
Static methods are bound at compile time, so they are not virtual. This means that they cannot be
overridden.
Overriding a static method would cause an error, because the compiler would not be able to determine
which method to call.
• In Java, you cannot override private or final methods. Private methods are not visible to any
other class and are limited to the class in which they are declared. Final methods cannot be overridden
because you have explicitly stated this is forbidden.
• However, private and final methods can be overloaded. This means that a class can have more
than one private or final method with the same name. However, a child class cannot override the private
or final methods of their base class.
• If you create a similar method with the same return type and same method arguments in a
child class, it will hide the super class method. This is known as method hiding.
• In Java, the return type can be the same or different in method overloading. However, you must
change the parameters. In method overriding, the return type must be the same or covariant.
• In method overloading, methods must have the same name and different signatures. In method
overriding, methods must have the same name and same signature.
• If there are two methods of the same signature within a class in the program, then an ambiguity error
occurs. This means that method overloading has no relation with return-type.
• In method overriding, the overriding method must take the same number and type of parameters as
the overridden method. The return type must not change. However, if the method returns an object, a
subclass of that object is allowed as the return type.
• The overriding method can throw any unchecked exceptions, regardless of whether the overridden
method throws exceptions.
• Method overriding is a feature of object-oriented programming that allows a subclass to provide its
own implementation for a method that is inherited from a superclass.
String model;
String color;
this.model=model;
this.color=color;
public:
private:
members declared as private are only accessible within the class in which they are declared.
protected:
members declared as protected are accessible within the class in which they are declared, in any
subclass of that class, and in any class in the same package as that class.
members declared without an access modifier are accessible within the class in which they are declared
and in any class in the same package as that class.
int defaultVariable;
// ...
// ...
// ...
void defaultMethod() {
// ...
13. What is the difference between Parent P = new Child() and Child C = new Child() where Parent is
a super class and Child is a base class?
In the 1st case Parent class is used as a reference so the methods and variables defined in parent class
alone are accessible.
In 2nd case Child class is used as a reference so that all methods of parent class can be accessed as well
as the extra methods of child class(if present) can also be accessed.
14. What is the use of final keyword in a variable, method and class?
Variable: A final variable is a constant, meaning its value cannot change. For example, if num is a final
variable initialized with the value 10, its value cannot be changed.
Method: A final method cannot be overridden by any subclass. Once a method is declared as final in a
superclass, it cannot be modified or overridden in any of its subclasses.
Class: A final class cannot be inherited or extended by any other class.
final is a keyword used in Java to restrict the modification of a variable, method, or class. finally is a block
used in Java to ensure that a section of code is always executed, even if an exception is thrown. finalize is
a method in Java used to perform cleanup processing on an object before it is garbage collected.
In Java, the == operator compares the memory location of two objects, while the equals() method
compares the contents of two objects.
Here are some more details about the differences between == and equals() in Java:
==: is a Java operator that can compare primitive data types and objects. It compares the data for
primitive data types and addresses for objects.
equals(): is a method that compares two objects based on their memory locations.
==: compares the reference or memory location of objects in a heap, whether they point to the same
location or not.
equals(): compares the values of object1 and object2 regardless of where they are located in memory.
17. How many methods of String class have you used? Name them with example
In Java, String is immutable, meaning its value cannot be changed once created. StringBuffer and
StringBuilder are both mutable classes, meaning strings can change if you use the StringBuffer and
StringBuilder class.
Here are some other differences between String, StringBuffer, and StringBuilder:
Memory: String is more memory-efficient than StringBuffer and StringBuilder if the content doesn't
change frequently.
API: The StringBuilder class and the StringBuffer class have the same API.
Storage: String uses string constant pool to store values, while StringBuffer uses heap memory to store
objects.
In Java programming, it's considered best practice to use StringBuilder to replace normal Strings
concatenation. StringBuffer should be used when thread-safety is required.
19. Where are String values stored in memory? Why String class is immutable?
String intern pool serves exactly this purpose. Java String Pool is the special memory region where
Strings are stored by the JVM. Since Strings are immutable in Java, the JVM optimizes the amount of
memory allocated for them by storing only one copy of each literal String in the pool
In Java, a static block is a block of code that runs when a class is first loaded into memory. An instance
block is an element of a class that runs when an instance of the class is created.
Here are some more details about static blocks and instance blocks:
Static blocks: Also known as static initialization blocks, these blocks are used to initialize static variables
or call static methods. They can also be used to perform one-time computations or setup operations.
Instance blocks: Also known as instance initialization blocks, these blocks are used to initialize instance
data members. They serve the same two purposes as constructors. Instance blocks can be declared
inside classes but not inside any method. Instance block logic is common for all the objects.
21. What is the default value of instance variable and local variable?
Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for
object references it is null. Values can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class.
The second property is that instance variables are initialized to their default values when they are
declared. The default value for an int variable is 0, for a boolean variable, it is false, and for a String
variable, it is null.
Since static methods and static variables belong to the entire class, any non-static method can access
static methods and static variables without having to create an instance of the class.
Static variables can be used in any type of methods: static or non-static. Non-static variables cannot be
used inside static methods. It will throw a compile-time error. Static variables are memory efficient as
they are created only once per class.
After we have the class instance, we can get the public static method object by calling the getMethod
method. Once we hold the method object, we can invoke it simply by calling the invoke method. It's
worthwhile to explain the first argument of the invoke method.
Break statement stops the entire process of the loop. Continue statement only stops the current
iteration of the loop. Break also terminates the remaining iterations. Continue doesn't terminate the
next iterations; it resumes with the successive iterations
The main difference between while and do-while loops is the order in which the condition is checked
and the statements are executed.
In a while loop, the condition is checked before the statements are executed. In a do-while loop, the
statements are executed at least once before the condition is checked.
Here are some other differences between while and do-while loops:
Loop body execution: The body of a do-while loop will execute at least once, even if the condition is
false. The body of a while loop will only execute if the condition is true.
Loop type: A while loop is an entry-controlled loop, while a do-while loop is an exit-controlled loop.
Use cases: A do-while loop is used when you want the loop to execute at least once. For example, when
trying to access a resource that may require a retry.
28. What will happen if we don’t have break statement inside matching catch? Should default be the
last statement in a switch case block?
If a break statement is not used in a switch case, the program will execute the code for the matching
case and then continue to execute the code for all the cases that follow. This is known as "falling
through" to the next case.
The use of break statement in a switch case statement is optional. "Break" basically breaks the condition
in switch after it has been evaluated.
You don't need a break after any case label if it is the last one.
29. Can your switch statement accept long, double or float data type?
No, the switch statement does not accept long, double, or float data types as expressions. This is
because the switch statement requires a constant expression that can be evaluated at compile-time.
In Java, the switch statement works with the following primitive types and their wrappers: byte, short,
char, and int. It also allows switching on an enum or String.
In the C language, the switch statement does not support floating-point types (such as float and double),
long long, and pointers.
30. What is the hierarchy of throwable class? What are checked and unchecked exceptions?
The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of
the Object class. Throwable has two direct subclasses - Exception and Error. The Exception class is used
for exception conditions that the application may need to handle.
In general, errors are considered unrecoverable, while exceptions are recoverable. Errors are system-
level issues that are usually caused by serious problems. Exceptions are application-level anomalies that
can be caught and handled by the developer.
Errors and exceptions are both types of runtime errors, which means they occur during the execution of
a program. When an error occurs, your program will typically terminate abruptly. When an exception
occurs, you can catch and handle it to recover from the exceptional condition.
Errors and exceptions are subclasses of the Throwable Java class. The Error class represents critical
conditions that can not be caught and handled by the code of the program.
In Java, the throw keyword is used to explicitly throw an exception from a method or block of code. The
throws keyword is used in the method signature to declare the exceptions that a method can potentially
throw.
throws: Goes at the top of a method and says what exceptions it might throw.
No, the finally block must be associated with a try block. It follows the try and catch blocks and ensures
that the defined cleanup code is executed, even if no exceptions were thrown in the try block.
Use a single catch block to catch more than one type of exception by separating each exception type
with a vertical bar or pipe |. You can also use the multi-try catch to perform different tasks at the
occurrence of different exceptions.
In Java, all elements of an array are set to 0 by default. Data types like int, short, byte, and long arrays
are initialized with 0.
Garbage collection (GC) is a form of automatic memory management. During garbage collection, the
program searches for memory which is no longer referenced by the program and reclaims it. This frees
up memory for further use by the program.
Garbage collection is a fundamental feature of many modern programming languages, such as Java, C#,
and Python. It can help to improve the performance and reliability of programs, as well as reduce the
amount of memory required to run them.
There are two main types of garbage collection: reference counting and mark-and-sweep. Reference
counting tracks the number of references to each object in memory. When the number of references to
an object reaches zero, the object is considered to be garbage and is collected. Mark-and-sweep works
by scanning the memory for objects which are no longer referenced by the program. These objects are
then marked as garbage and are collected.
Garbage collection is a complex process, but it is an essential part of many modern programming
languages. It can help to improve the performance, reliability, and memory usage of programs.
GC or garbage collection runs, only when the JVM runs out of memory and it needs to free up space for
the running process. Additionally, there are objects to be released, which are not needed for the current
program. You cannot completely turn off GC, but there are ways to delay its execution
38. How do you read contents of a file? How do you write in a file?
There are a few ways to read the contents of a file in Java. One way is to use the FileReader class. This
class allows you to read the contents of a file one character at a time. Another way to read the contents
of a file is to use the BufferedReader class. This class allows you to read the contents of a file one line at
a time.
To write to a file in Java, you can use the FileWriter class. This class allows you to write the contents of a
file one character at a time. Another way to write to a file is to use the PrintWriter class. This class allows
you to write the contents of a file one line at a time.
Here is an example of how to read the contents of a file using the FileReader class:
import java.io.FileReader;
import java.io.IOException;
int c;
System.out.print((char) c);
fr.close();
A functional interface is an interface that contains exactly one abstract method. It can have any number
of default or static methods. Functional interfaces are also known as SAM interfaces, which stands for
Single Abstract Method interfaces.
Functional interfaces are used in Java 8 to represent functions. This allows functions to be passed as
arguments to methods and assigned to variables. Functional interfaces are also used in lambda
expressions, which are a concise way to write functions.
These interfaces are used in a variety of ways in Java. For example, the Runnable interface is used to
represent tasks that can be executed by a thread. The Comparator interface is used to compare objects.
The Callable interface is used to represent tasks that can be executed asynchronously. The Consumer
interface is used to represent operations that consume a value. The Predicate interface is used to
represent operations that return a boolean value. The Function interface is used to represent operations
that take one argument and return a value. The Supplier interface is used to represent operations that
return a value without taking any arguments.
Functional interfaces are a powerful tool that can be used to make Java code more concise and readable.
Marker interfaces in Java are interfaces that don't have any methods or constants inside them. It
provides run-time type information about objects, so the compiler and JVM have additional information
about the object. A marker interface is also called a tagging interface.
Multithreading can improve the performance of a program by allowing it to take advantage of multiple
CPU cores. It can also make a program more responsive to user input, because multiple threads can
handle different tasks at the same time.
The main difference between a process and a thread is that a process has its own memory space, while
threads share the process's memory space. This means that threads can communicate with each other
easily by sharing data in memory. However, it also means that threads need to be careful not to interfere
with each other's data.
Here is an analogy to help you understand the difference between processes and threads:
Imagine a restaurant. The restaurant is like a process, and the tables are like threads. Each table can seat
a different group of customers, and the customers can order and eat their food independently of the
other customers at the restaurant. However, the customers all share the same kitchen, so they need to
be careful not to get in each other's way.
In the same way, processes share the same operating system resources, such as the CPU and memory.
However, each process has its own memory space, so the processes cannot directly access each other's
data.
Multithreading is a powerful technique that can be used to improve the performance and
responsiveness of programs. However, it is important to use multithreading carefully to avoid problems
such as race conditions and deadlocks.
42. What is the difference between thread class and runnable interface?
Methods
The Thread class has multiple methods, including start(), run(), setName(), and getName(). The Runnable
interface has only one abstract method, run().
Threads
The Thread class creates a new thread, while implementing the Runnable interface doesn't.
Memory
In Runnable, multiple threads share the same object, so require less memory.
Inheritance
Java only allows single inheritance, so if you inherit from Thread you won't be able to inherit from any
other class. Implementing the Runnable interface doesn't have this limitation.
When you implement Runnable, both Task and Executor are loosely coupled. When you extend Thread,
they are tightly coupled.
Default methods: Default methods are methods that have a body and can be implemented in the
interface itself. This is in contrast to abstract methods, which must be implemented in the classes that
implement the interface.
Default methods were introduced to provide backward compatibility for old interfaces so that they can
have new methods without affecting existing code. For example, the List interface was extended in Java 8
to add a new method called forEach(). This method takes a Consumer object as a parameter and iterates
over the list, calling the accept() method on the Consumer object for each element in the list.
Static methods: Static methods are methods that are associated with the interface itself, rather than
with any particular object. This means that they cannot be called on instances of the interface.
Static methods were introduced to provide a place to put utility methods that are related to the
interface. For example, the List interface has a static method called of() that takes a variable number of
arguments and returns a new List containing those arguments.
Both default and static methods can be useful for improving the functionality and flexibility of interfaces.
However, it is important to use them sparingly, as too many methods can make the interface difficult to
understand and use
In Java, Collection is an interface that groups objects into a single unit. Collections are a utility class that
provides static methods for performing operations on collections.
Here are some differences between Collection and Collections:
Interface vs class
Methods: Collection provides methods for data structure, while Collections provides static methods for
various operations on a collection.
Operations: Collection is the root of the Java collections Framework, while Collections provides static
methods for operations like sorting, searching, and reversing.
Static methods: Collection doesn't have all static methods, but Collections consists of all static methods.
Collection, Set, Queue, and List all are interfaces. Set, Queue and List are extended by the Collection
interface. PriorityQueue, HashSet, LinkedList, and Stack all are classes or the implementation of these
interfaces. It is not mandatory that a class implements just one interface
46. What are the sub interfaces and sub classes of List, Set and Map interface?
List implementation classes are Array List, LinkedList. Set implementation classes are HashSet,
LinkedHashSet, and TreeSet. Map implementation classes are HashMap, HashTable, TreeMap,
ConcurrentHashMap, and LinkedHashMap. The list provides get() method to get the element at a
specified index.
47. What is the difference between ArrayList and LinkedList? Which one is faster in insertion,
deletion and random access memory?
48. What is the difference between singly linkedlist, doubly linkedlist and circular linkedlist?
53. How to convert Array into Arraylist and Arraylist into Array?
54. How to convert Set into List?
60. What are the difference methods of Collections class have you used ?
The Collections class in Java provides a number of static methods that can be used to operate on
collections. These methods can be used in testing to perform a variety of tasks, such as sorting
collections, searching for elements, and performing mathematical operations on collections.
• Some of the most commonly used Collections class methods in testing include:
• containsAll(): Returns true if a collection contains all of the elements of another collection.
These methods can be used to test a variety of different types of collections, such as arrays, lists, and
sets. They can also be used to test collections of different types of objects, such as strings, numbers, and
objects.
For example, the sort() method can be used to test a collection of strings to make sure that they are
sorted in alphabetical order. The binarySearch() method can be used to test a collection of integers to
make sure that a specified integer is present in the collection. And the frequency() method can be used
to test a collection of objects to make sure that a specified object occurs a certain number of times in the
collection.
The Collections class methods can be a valuable tool for testing collections of data. They can help to
ensure that collections are sorted, searched, and manipulated correctly.
while (iterator.hasPrevious()) {
System.out.println(string);
A ListIterator can be used to traverse the elements in the forward direction as well as the reverse
direction in a LinkedList. The method hasPrevious( ) in ListIterator returns true if there are more
elements in the LinkedList while traversing in the reverse direction and false otherwise
Comparable interface can be used to provide single way of sorting whereas Comparator interface is used
to provide different ways of sorting. For using Comparable, Class needs to implement it whereas for
using Comparator we don't need to make any change in the class.
47. Why can we compare Strings without implementing compare() or compareTo methods?
48. Because strings are immutable, and the String class provides a number of methods for
comparing strings without needing to implement compare() or compareTo().
49. The equals() method compares two strings lexicographically, and returns true if they are
equal. The compareTo() method also compares two strings lexicographically, but returns
an integer value indicating whether the first string is less than, equal to, or greater than
the second string.
50. The String class also provides a number of other methods for comparing strings, such as
startsWith(), endsWith(), and contains(). These methods can be used to determine
whether a string contains a particular substring, or whether it starts or ends with a
particular character or sequence of characters.
Abstract classes and interfaces are both used to define an interface and defer its implementation.
However, they have some differences:
Abstract classes
Provide a base class for subclasses to inherit from. They can have implemented and abstract methods.
Abstract classes can also have fields and properties. A class can extend only one abstract class.
Interfaces
Define a set of methods that a class must implement. They can only have abstract methods. Interfaces
can only have properties. A class can implement multiple interfaces.
An abstract class is a class that is designed to be specifically used as a base class. An abstract class
contains at least one pure virtual function.
Abstract class and interface are both used to define contracts in object-oriented programming, but there
are some key differences between them.
Definition: An abstract class is a class that cannot be instantiated and can contain both abstract and non-
abstract methods. An interface, on the other hand, is a contract that specifies a set of methods that a
class must implement.
Method implementation: In an abstract class, some methods can be implemented, while others are left
abstract, meaning that they have no implementation and must be overridden by concrete subclasses. In
contrast, all methods in an interface are by default abstract and must be implemented by any class that
implements the interface.
Inheritance: A class can inherit from only one abstract class, but it can implement multiple interfaces.
This is because an abstract class represents a type of object, while an interface represents a set of
behaviors.
Access modifiers: Abstract classes can have access modifiers such as public, protected, and private for
their methods and properties, while interfaces can only have public access.
Variables: An abstract class can have member variables, while an interface cannot.
In summary, abstract classes are used to provide a base class for concrete subclasses to inherit from,
while interfaces are used to define a set of methods that a class must implement. Abstract classes can
have implemented and abstract methods, while interfaces can only have abstract methods. Classes can
inherit from only one abstract class, but can implement multiple interfaces.
As we know that abstraction refers to hiding the internal implementation of the feature and only
showing the functionality to the users. i.e. showing only the required features, and hiding how those
features are implemented behind the scene. Whereas, an Interface is another way to achieve abstraction
in java. Both abstract class and interface are used for abstraction, henceforth Interface and Abstract Class
are required prerequisites.
Type of methods: Interface can have only abstract methods. Whereas, an abstract class can have
abstract method and concrete methods. From Java 8, it can have default and static methods also. From
Java 9, it can have private concrete methods as well.
Note : Concrete methods are those methods which has their complete definition but they can also be
overriden in the inherited class. However, if we make the concrete method as “FINAL” it cannot be
overrided in the inherited class because declaring a method as final means – its implementation is
complete.
Final Variables: Variables declared in a Java interface are by default final. An abstract class can contain
non-final variables.
Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface
has only static and final variables.
Implementation: Abstract class can provide the implementation of the interface. Interface can’t provide
the implementation of an abstract class.
Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and
an abstract class can be extended using the keyword “extends”.
Multiple implementations: An interface can extend one or more Java interfaces; an abstract class can
extend another Java class and implement multiple Java interfaces.
Multiple Inheritance: Multiple inheritance can be partially achieved by the use of interfaces , whereas
the same can’t be done by the use of abstract classes. Because in Java, one class can implement multiple
Interfaces, but one class cannot extend from multiple other classes because that’s just not possible in
java as that would lead to the diamond problem.
Accessibility of Data Members: Members(variables) of a Java interface are final by default. A Java
abstract class can have class members like private, protected, etc.
Cannot be instantiated: Abstract classes cannot be directly instantiated, which means you cannot create
objects of an abstract class.
Contains at least one pure virtual function: Abstract classes must contain at least one pure virtual
function, which means that the function has no implementation and must be implemented by any
derived classes.
Can contain both abstract and non-abstract methods: Abstract classes can have both abstract and non-
abstract methods. Non-abstract methods have a complete implementation and can be called directly.
Can have constructors and destructors: Abstract classes can have constructors and destructors like any
other class.
Can have member variables: Abstract classes can have member variables, which are variables that
belong to an object of the class.
Can be used as a base class: Abstract classes can be used as a base class for other classes, which means
that they can be inherited by other classes.
Overall, abstract classes are used to define a common interface or behavior that can be shared by
multiple related classes, but with specific implementations in each derived class.
Yes, private methods are possible in interfaces in Java 9 and later. Before Java 9, creating private
methods in interfaces caused a compile-time error
Yes! Abstract classes can have constructors! Yes, when we define a class to be an Abstract Class it cannot
be instantiated but that does not mean an Abstract class cannot have a constructor. Each abstract class
must have a concrete subclass which will implement the abstract methods of that abstract class.
Yes, you can define an abstract class without any abstract methods.
In Java, an abstract class means that you can't create an object of the class. Declaring a class abstract
indicates that the class is incomplete and can only be sub classed.
Abstract classes are used to implement a general logic that can be implemented by other classes. They
hide the implementation and show the function definition to the user.
An example of an abstract class in the JDK is AbstractMap. Its subclasses, which include HashMap,
TreeMap, and ConcurrentHashMap, share many methods that AbstractMap defines.
class MyClass:
self.name = name
self.age = age
super keyword is used to access methods of the parent class while this is used to access methods of the
current class. this keyword is a reserved keyword in java i.e, we can't use it as an identifier. It is used to
refer current class's instance as well as static members.
package javaTpoint.MicrosoftJava;
class Animal{
//default constructor
Cat()
// default constructor
SuperExample1()
super();
new SuperExample1();
System.out.println("Inside Main");
The 'super' keyword allows referencing the parent class or superclass of a subclass in Java. It is often
employed to access members (fields or methods) of the superclass that have been overridden in the
subclass. You can call the superclass's method from within the subclass using super. methodName().
Use the findElement(By.xpath()) method to locate all the rows of a web table.
Iterate through the rows to find a specific cell based on its row and column index.
You can also use the getText() function to get the text of a row or cell. For example, you can use the
XPath //*[@id=\”leftcontainer\”]/table/tbody/tr to find the second row and get its text. You can also use
the XPath //*[@id=\”leftcontainer\”]/table/tbody/tr/td to find the second cell in the second row and get
its text.
To fetch data from the last row of a dynamic web table, you can use the findElement(By.xpath()) method
in Selenium:
Use the findElement(By.xpath()) method to locate all the rows of the web table.
Iterate through the rows to find a specific cell based on its row and column index.
You can also use the get(row).findElements(By.tagName("td")) method to iterate through each column
and fetch values.
Get the handle of the parent window using the command: String parentWindowHandle = driver. ...
Find the element on the web page using an ID which is an element locator.
Iterate through child windows. Get the handles of all the windows that are currently open using the
command: Set<String> allWindowHandles = driver.getWindowHandles(); which returns the set of
handles. Use the SwitchTo command to switch to the desired window and also pass the URL of the web
page.
How do you switch from one window to another window?
To switch from one window to another window in Selenium WebDriver using Java, you can use the
following steps:
Get the handles of all the windows that are currently open using the driver.getWindowHandles()
method. This will return a set of handles.
Use the switchTo().window() method to switch to the desired window. Pass the handle of the window
you want to switch to as a parameter to this method.
For example, the following code will switch to the second window that is open:
driver.switchTo().window(secondWindowHandle);
To handle alerts in Selenium WebDriver, you can use the following methods:
switchTo(): Switches the control from the parent window to the alert window
An alert is a small message box that appears on the screen to give information, give a warning, or ask
permission. There are three types of alerts:
There is a condition called alertIsPresent which we will use to check for alerts. It shall wait for a specified
amount of time for the alert after which it shall throw an exception.
You can also use the switchTo().defaultContent() method to switch focus to the first frame on the page.
For iFrames, this switches the context back to the main document.
The index of a frame starts at 0. If the frame is not found, a NoSuchFrameException is thrown.
In such cases, you can use the iselementpresent method to check if the element exists on the page
before trying to interact with it. The iselementpresent method returns a boolean value indicating
whether the element is present on the page. If the element is present, the method returns True;
otherwise, it returns False.
XPath and CSS locators are both used to locate elements on web pages. However, they differ in the
following ways:
Direction: CSS locators only move down the HTML tree, while XPath can move both up and down.
Flow: CSS locators have a one-directional flow, while XPath has a bidirectional flow.
Complexity: CSS locators are simpler and faster, while XPath is more flexible and powerful.
Navigability: CSS locators are better for straightforward HTML element selection, while XPath can
navigate complex and dynamic web page structures.
Data extraction: XPath is more versatile and powerful for data extraction in sites with complex layouts or
non-HTML data.
Selectors: CSS selectors can be divided into five categories, including simple selectors and combinator
selectors.
XPath is the XML Path Language, which is used to uniquely identify or address parts of an XML
document. An XPath expression can be used to search through an XML document and extract
information from any part of the document.
To do this, we find the element using an attribute that's unique to the element. You can use name, ID,
XPath, etc. to identify an element. In the above example, we're using the element's name. As we know
that a dropdown can have multiple values, we use the object of the element to select a value from the
dropdown
In Selenium, the Action class is an interface that represents single user interactions. The Actions class is a
user-facing API that emulates complex user gestures.
Actions: Builds and performs composite actions, which are sequences of multiple actions.
You can string a bunch of actions together using Actions. Once you call build(), it will store that set of
steps as an Action.
Double click action in Selenium web driver can be done using Actions class. Actions class is a predefined
class in Selenium web driver used to perform multiple keyboard and mouse operations such as Right
Click, Drag and Drop, etc. Actions actions = new Actions(driver); WebElement elementLocator = driver.
The Robot class in Selenium is a Java-based utility class that provides a way to simulate keyboard and
mouse events on the screen. It allows testers to automate tasks that cannot be done using Selenium's
built-in methods, such as pressing a key on the keyboard or moving the mouse cursor to a specific
location.
The close() method is used to close the current browser window or tab.
It closes only the window or tab that is currently being controlled by the
WebDriver instance.
Can you explain about some common exceptions in Selenium?
Let's understand some of the common Selenium exceptions in detail: WebDriverException: The
WebDriverException occurs when it tries to perform an action when the webDriver connection is in a
closed state. TimeOutException: TimeOutException occurs when a command takes more time than the
specified or default wait time
When defining an object as ThreadLocal you are essentially telling the object to create a new instance for
each thread which accesses it. All object exposed and used under this object should be local and
exclusive to the thread using the object
50. Where have you used List, Set and Map in Selenium?
• List, Set, and Map are common collection types used in Selenium. They are used to store
WebElements such as window handles, objects, and key values. The right collection type depends on the
context and requirements of the automation task.
• Here are some considerations for using List, Set, and Map:
List
• Use List if you need to access elements using the index. List allows duplicate values.
Set
• Use Set if you need a group of unique elements. Set does not allow duplicate values.
Map
• Use Map if objects contain key and value pairs. Map can store data in the form of key-value
pairs.
• Here are some examples of using List, Set, and Map in Selenium:
• Using a list to store each cell element as it comes into a web element
Method overloading occurs when a class has multiple methods with the same name but different
parameters.
Implicit wait: When different time stamps are used, such as SECONDS, MINUTES, HOURS, etc.
Click method: The click method is overloaded with different parameters, such as WebElement, By
(locator), and By with an additional index parameter. This allows users to click on elements in different
ways, providing flexibility in Selenium test scripts.
Method overloading can also be achieved by changing the data type of arguments or the number of
arguments
SearchContext is the topmost interface in Selenium API which has two methods - findElement() and
findElements(). Selenium WebDriver interface has many abstract methods like get(String url), quit(),
close(), getWindowHandle(), getWindowHandles(), getTitle() etc.
The WebDriver class focuses on driving the browser in a broad sense. It loads pages, it switches to
different windows/frames, gets the page title etc. Broad actions that aren't specific to an element on the
page. WebElement concentrates on interacting with a specific element that you've located.
What is the super interface of WebDriver? What is the hierarchy of WebDriver?
The SearchContext interface is the super interface of the Selenium WebDriver. It's the topmost interface
in the WebDriver hierarchy, and it has two methods: findElement() and findElements(). The WebDriver
and WebElement interfaces both extend the SearchContext interface.
WebDriver is a collection of related methods. WebElements are the buttons, text boxes, checkboxes,
drop-down menus, and hyperlinks on a web application.
• get():
• getCurrentUrl():
• getTitle():
• findElements():
• findElement():
• getPageSource():
• close():
findElements
driver.findElements() is used to find a List of webElements matching the locator passed as
parameter.
List<WebElement> elements = driver.findElements(By locator);
In case the same locator matches multiple web elements then findElements method returns the
first web element found.
In case the locator passed to findElements() method leads to no element then a List of 0 size is
returned instead of an exception.
What are waits in selenium? Difference between implicit wait and explicit wait?
Condition: Implicit wait waits for an element to appear on the page, while explicit wait waits for a
specific condition, such as the presence of an element or the element to be clickable. Scope: Implicit
wait applies globally, while explicit wait applies locally to a specific element.
In XPath, the single forward slash ("/") is used to select the immediate child of the current node, while
the double forward slash ("//") is used to select all descendant nodes regardless of their depth in the
XML document
In CSS, the asterisk (*) is a universal selector that can be used to select all elements in
an HTML page. It can also be used to select specific elements within a nested
hierarchy of elements. The asterisk is a wildcard symbol that means everything.
Here are some other CSS selectors:
Class selector: Uses a period character followed by the class name to select HTML
elements with a specific class attribute.
Attribute selector: Uses square brackets to target elements based on the presence of
and/or the value of HTML attributes associated with the element.
Id selector: Uses the id attribute of an HTML element to select a specific element.
CSS selectors allow developers to target and style webpage HTML elements. They let
you determine which elements you want to apply CSS styling rules to.
Over-Dependency on Technology.
Data management.
What are the challenges you faced while working with IE browser?
The major challenges in using Selenium are handling pop-ups, dynamic web content, mobile testing,
captcha and scalability.
Handling Pop-Ups.
Mobile Testing.
Captcha.
Scalability.
Final Thoughts.
Page Factory is a design pattern in Selenium that simplifies the process of creating Page Objects. It's an
optimized, inbuilt Page Object Model framework concept for Selenium WebDriver.
Page Factory reduces the boilerplate code needed to create Page Objects and makes the automation
code more maintainable and readable. It's also used to initialize Page objects or to instantiate the Page
object itself.
Page Factory is a class provided by Selenium WebDriver to support Page Object Design patterns. In Page
Factory, testers use the @FindBy annotation to locate and declare web elements using different locators.
The initElements method is used to initialize web elements.
Page Factory is one way of implementing the Page Object Model. The Page Object Model is a way of
representing an application in a test framework. For every "page" in the application, a Page Object is
created to reference the "page".
How to read data from excel? Difference between HSSFWorkbook and XSSFWorkbook?
• To read data from Excel in Selenium, you can:
• Create an instance of the Workbook class and open the Excel file.
• Process the cell value based on its data type using the DataFormatter.
• You can use the Apache POI library to read and write Excel files in Java. This library can read
and write both XLS and XLSX file formats. To read XLS files, you can use the HSSF implementation of the
POI library. To read XLSX files, you can use the XSSF implementation of the POI library.
• You can also use the WorkbookFactory class to create the appropriate workbook. The two
classes that implement the “Workbook” interface are HSSFWorkbook and XSSFWorkbook.
CODING