Java Questions
Java Questions
The classes in java.util package handles only objects and hence wrapper classes help in this case also.
Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
Class loaders are responsible for loading Java classes dynamically to the JVM (Java Virtual Machine)
during runtime. They're also part of the JRE (Java Runtime Environment). Therefore, the JVM doesn't
need to know about the underlying files or file systems in order to run Java programs thanks to class
loaders.
Furthermore, these Java classes aren't loaded into memory all at once, but rather when they're
required by an application. This is where class loaders come into the picture. They're responsible for
loading classes into memory.
What are wrapper classes and why do we need? Difference between int and Integer?
A wrapper class wraps (encloses) around a data type and gives it an object appearance. Wrapper
classes are final and immutable. Two concepts are there in the wrapper classes namely autoboxing
and unboxing.
Passed as a parameter to a method that expects an object of the corresponding wrapper class.
int, being a primitive data type has got less flexibility. We can only store the binary value of an
integer in it.
Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and
manipulating an int data.
Integer is a class and thus it can call various in-built methods defined in the class. Variables of type
Integer store references to Integer objects, just as with any other reference (object) type.
Examples:
// Valid
int n = 20;
//valid
Integer n = 45;
// Valid
Integer.parseInt("10");
// Not Valid
int.parseInt("10");
Casting to String Variable : We can’t assign a String value (containing an integer only) to an int
variable directly or even by casting. However, we can assign a String to an object of Integer type
using the Integer(String) constructor. We can even use parseInt(String) to convert a String literal to
an int value.
// difference between
// int a = (int)"123";
// int c="123";
int b = Integer.parseInt("123");
Output:
133.1
Direct Conversion of value to other base : We can directly convert an integer value stored in Integer
class to Binary, Octal or Hexadecimal format using toBinaryString(), toOctalString() or toHexString()
respectively. This is not possible in a variable of int type.
// difference between
Output:
1111011
173
7b
Performing operations on data : Integer class also allows us to reverse our number or rotate it left or
right using reverse(), rotateLeft() and rotateRight() respectively. We need to define our own logic to
perform these operations on an int variable as its not an inbuilt class.
// difference between
// (12)10->(1100)2 ->
// (12)10->(1100)2 ->
// -> (805306368)10
// int is of 32 bits
Output:
Left Rotate : 48
Right rotate : 3
Reverse : 805306368
Flexibility : Integer wrapper class provides us more flexibility to the existing int datatype. We are
able to perform many operations on an int value besides the predefined operators. Integer class is
used where we need to treat an int variable like an object. Since Wrapper classes inherit Object
class, they can be used in collections with Object reference or generics. Thus we are adding the
property of nullability to the existing int data type.
Since Java 5, we have the concept of auto-boxing wherein a primitive data type is converted into a
wrapper class and vice versa automatically. Hence, we can perform any arithmetic or logical
operation between any primitive data type and any Wrapper class.
// auto-boxing
import java.util.function.Function;
import java.util.function.Function;
int b = 2;
double c = 3.1;
int d2 = a + d;
+ (a + d));
Output:
Besides Integer, we have more wrapper classes in Java corresponding to the data types. These are
given as follows :
What is immutable classes? Name 5 immutable classes in Java? How to make a class immutable?
Immutable class in java means that once an object is created, we cannot change its content. In Java,
all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.
The class must be declared as final so that child classes can’t be created.
Data members in the class must be declared private so that direct access is not allowed.
Data members in the class must be declared as final so that we can’t change the value of it after
object creation.
A parameterized constructor should initialize all the fields performing a deep copy so that data
members can’t be modified with an object reference.
Deep Copy of objects should be performed in the getter methods to return a copy rather than
returning the actual object reference)
What are OOPS concepts? Explain them. What all OOPS concepts have you used in your framework?
ABSTRACTION
Abstraction is the methodology of hiding the implementation of
internal details and showing the functionality to the users.
In Page Object Model design pattern, we write locators (such as id,
name, xpath etc.,) and the methods in a Page Class. We utilize these
locators in tests but we can’t see the implementation of the
methods. Literally we hide the implementations of the locators from
the tests.
In Java, abstraction is achieved by interfaces and abstract classes.
Using interfaces, we can achieve 100% abstraction
2. INTERFACE
Basic statement we all know in Selenium is WebDriver driver =
new FirefoxDriver();
INHERITANCE
The mechanism in Java by which one class acquires the properties
(instance variables) and functionalities of another class is known as
Inheritance.
We extend the Base Class in other classes such as Tests and Utility
Class.
Here we extend one class (Base Class like WebDriver Interface) into
other class (like Tests, Utility Class) is known as Inheritance.
POLYMORPHISM
Polymorphism allows us to perform a task in multiple ways.
METHOD OVERLOADING
We use Implicit wait in Selenium. Implicit wait is an example of
overloading. In Implicit wait we use different time stamps such as
SECONDS, MINUTES, HOURS etc.,
ENCAPSULATION
All the classes in a framework are an example of Encapsulation. In
POM classes, we declare the data members using @FindBy and
initialization of data members will be done using Constructor to
utilize those in methods.
WEB ELEMENT
Web element is an interface used to identify the elements in a web
page.
WEBDRIVER
WebDriver is an interface used to launch different browsers such as
Firefox, Chrome, Internet Explorer, Safari etc.,
FIND BY
FindBy is an annotation used in Page Object Model design pattern to
identify the elements.
What is Object class in Java? Explain role and importance of toString, equal and hashcode method?
The Object class is the parent class of all the classes in java by default. In other words, it
is the topmost class of java. The Object class is beneficial if you want to refer any object
whose type you don't know.
What is method overloading and overriding? What is upcasting and down casting?
The differences between Method Overloading and Method Overriding in Java
are as follows:
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
Method Overloading:
Method Overloading is a Compile time polymorphism. In method
overloading, more than one method shares the same method name with a
different signature in the class. In method overloading, the return type can or
can not be the same, but we have to change the parameter because, in java,
we can not achieve the method overloading by changing only the return type
of the method.
import java.io.*;
class MethodOverloadingEx {
Output
add() with 2 parameters
10
add() with 3 parameters
17
Method Overriding:
Method Overriding is a Run time polymorphism. In method overriding, the
derived class provides the specific implementation of the method that is
already provided by the base class or parent class. In method overriding, the
return type must be the same or co-variant (return type may vary in the same
direction as the derived class).
Example: Method Overriding
Java
C++
import java.io.*;
class Animal {
void eat()
{
System.out.println("eat() method of base class");
System.out.println("eating.");
}
}
void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}
}
class MethodOverridingEx {
d1.eat();
a1.eat();
Output
eat() method of derived class
Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.
Output explanation:
Here, we can see that a method eat() has overridden in the derived class
name Dog that is already provided by the base class name Animal. When
we create the instance of class Dog and call the eat() method, we see that
only derived class eat() method run instead of base class method eat(), and
When we create the instance of class Animal and call the eat() method, we
see that only base class eat() method run instead of derived class method
eat().
Typecasting is one of the most important concepts which basically deals with
the conversion of one data type to another datatype implicitly or explicitly. In
this article, the concept of typecasting for objects is discussed.
Just like the data types, the objects can also be typecasted. However, in
objects, there are only two types of objects, i.e. parent object and child
object. Therefore, typecasting of objects basically means that one type of
object (i.e.) child or parent to another. There are two types of typecasting.
They are:
Java
// Parent class
class Parent {
String name;
// Child class
class Child extends Parent {
int id;
// Driver code
public static void main(String[] args)
{
// Upcasting
Parent p = new Child();
p.name = "GeeksforGeeks";
// Downcasting Explicitly
Child c = (Child)p;
c.id = 1;
System.out.println(c.name);
System.out.println(c.id);
c.method();
}
}
Output
GeeksforGeeks
Method from Child
GeeksforGeeks
1
Method from Child
An illustrative figure of the above program:
1. Syntax of Upcasting:
Child c = (Child)p;
1. Downcasting has to be done externally and due to downcasting a
child object can acquire the properties of the parent object.
c.name = p.name;
i.e., c.name = "GeeksforGeeks"
Can we overload private and final methods? Can we override static methods?
Not so important
No, we cannot override static methods because method overriding is based on dynamic
binding at runtime and the static methods are bonded using static binding at compile time.
So, we cannot override static methods. The calling of method depends upon the type of
object that calls the static method.
Can we override private and final methods?
No, we cannot override private or static methods in Java. Private methods in Java are
not visible to any other class which limits their scope to the class in which they are declared.
You can declare some or all of a class's methods final. You use the final keyword in a
method declaration to indicate that the method cannot be overridden by subclasses. The
Object class does this—a number of its methods are final
class IntegralOperations {
Output
prog.java:13: error: add(int,int) in child cannot override
add(int,int) in IntegralOperations
@Override int add(int a, int b) { return a - b; }
^
overridden method is final
prog.java:16: error: subtract(int,int) in child cannot
override subtract(int,int) in IntegralOperations
@Override int subtract(int a, int b) { return a * b; }
^
overridden method is final
2 errors
As evident from the above Output, attempting to Override a final
method causes a compile-time error.
This proves that final methods cannot be overridden in Java.
Why Does The final Keyword Prevent Overriding?
In the beginning, it was discussed that methods to be Overridden
follow Dynamic Method Dispatch (late binding)But the methods which are
declared as final follow static binding (early binding), which means that the
method definition will be grouped with a body at compile-time itself.
In other words, JVM must know exactly which method to call at compile-
time.To accomplish this, for every final method definition there must be a
unique body. But if Overriding is allowed then there can be multiple bodies
for a method definition and then the compiler won’t be able to choose one of
them.
This issue is seen in the above example where we have two bodies each for
add and subtract methods. This prompts the compiler to throw an error at
compile-time. In this way, the final keyword prevents Overriding and guards
the semantics of a method.
An overriding method can throw any unchecked exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the
overridden method.
Autoboxing is the automatic conversion that the Java compiler makes between the
primitive types and their corresponding object wrapper classes. For example,
converting an int to an Integer, a double to a Double, and so on. If the conversion goes the
other way, this is called unboxing.
// Main class
class GFG {
// Print statements
System.out.println("Value of i:" + i);
System.out.println("Value of i1: " + i1);
// Autoboxing of character
Character gfg = 'a';
// Auto-unboxing of Character
char ch = gfg;
// Print statements
System.out.println("Value of ch: " + ch);
System.out.println(" Value of gfg: " + gfg);
}
}
Output:
What is abstract class and interface? Difference between abstract class and interface? Can we have
private methods in interfaces? Can we have constructor in abstract classes? Can we make a class
abstract without any abstract methods?
The two are separate concepts, though obviously you can't have an abstract
method in a non-abstract class. You can even have abstract classes
with final methods but never the other way around.
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.
An interface can have private methods since Java 9 version. These methods are visible
only inside the class/interface, so it's recommended to use private methods for confidential
code. That's the reason behind the addition of private methods in interfaces.
// Class 1
// Helper abstract class
abstract class Shape {
// Declare fields
String objectName = " ";
// Method
// Non-abstract methods
// Having as default implementation
public void moveTo(int x, int y)
{
System.out.println(this.objectName + " "
+ "has been moved to"
+ " x = " + x + " and y = " + y);
}
// Method 2
// Abstract methods which will be
// implemented by its subclass(es)
abstract public double area();
abstract public void draw();
}
// Class 2
// Helper class extending Class 1
class Rectangle extends Shape {
// Attributes of rectangle
int length, width;
// Constructor
Rectangle(int length, int width, String name)
{
// Super keyword refers to current instance itself
super(name);
// Method 1
// To draw rectangle
@Override public void draw()
{
System.out.println("Rectangle has been drawn ");
}
// Method 2
// To compute rectangle area
@Override public double area()
{
// Length * Breadth
return (double)(length * width);
}
}
// Class 3
// Helper class extending Class 1
class Circle extends Shape {
// Attributes of a Circle
double pi = 3.14;
int radius;
// Constructor
Circle(int radius, String name)
{
// Super keyword refers to parent class
super(name);
// This keyword refers to current instance itself
this.radius = radius;
}
// Method 1
// To draw circle
@Override public void draw()
{
// Print statement
System.out.println("Circle has been drawn ");
}
// Method 2
// To compute circle area
@Override public double area()
{
return (double)((pi * radius * radius));
}
}
// Class 4
// Main class
class GFG {
rect.moveTo(1, 2);
System.out.println(" ");
circle.moveTo(2, 4);
}
}
Output
Area of rectangle: 6.0
Rectangle has been moved to x = 1 and y = 2
Example 1-B:
Java
// Interface
interface Shape {
// Abstract method
void draw();
double area();
}
// Class 1
// Helper class
class Rectangle implements Shape {
// constructor
Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
// Class 2
// Helper class
class Circle implements Shape {
double pi = 3.14;
int radius;
// constructor
Circle(int radius) { this.radius = radius; }
// Class 3
// Main class
class GFG {
Output
Area of rectangle: 6.0
Area of circle: 12.56
When to use what?
Consider using abstract classes if any of these statements apply to your
situation:
In the java application, there are some related classes that need to
share some lines of code then you can put these lines of code
within the abstract class and this abstract class should be extended
by all these related classes.
You can define the non-static or non-final field(s) in the abstract
class so that via a method you can access and modify the state of
the object to which they belong.
You can expect that the classes that extend an abstract class have
many common methods or fields, or require access modifiers other
than public (such as protected and private).
Consider using interfaces if any of these statements apply to your situation:
It is total abstraction, All methods declared within an interface must
be implemented by the class(es) that implements this interface.
A class can implement more than one interface. It is called multiple
inheritances.
You want to specify the behavior of a particular data type but are
not concerned about who implements its behavior
1. Introduction
Abstraction is one of the Object-Oriented programming key
features. It allows us to hide the implementation
complexities just by providing functionalities via simpler
interfaces. In Java, we achieve abstraction by using either
an interface or an abstract class.
In this article, we'll discuss when to use an interface and when to
use an abstract class while designing applications. Also, the key
differences between them and which one to choose based on
what we're trying to achieve.
@Override
protected void start() {
// code implementation details on starting a car.
}
@Override
protected void stop() {
// code implementation details on stopping a car.
}
@Override
protected void drive() {
// code implementation details on start driving a car.
}
@Override
protected void changeGear() {
// code implementation details on changing the car gear.
}
@Override
protected void reverse() {
// code implementation details on reverse driving a car.
}
}
In the above code, the Vehicle class has been defined as abstract
along with other abstract methods. It provides generic operations
of any real-world vehicle and also has several common
functionalities. The Car class, which extends the Vehicle class,
overrides all the methods by providing the car's implementation
details (“Car is a Vehicle”).
Hence, we defined the Vehicle class as abstract in which the
functionalities can be implemented by any individual real vehicle
like cars and buses. For example, in the real world, starting a car
and bus is never going to be the same (each of them needs
different implementation details).
Now, let's consider a simple unit test that makes use of the above
code:
@Test
void givenVehicle_whenNeedToDrive_thenStart() {
car.start();
car.drive();
car.changeGear();
car.stop();
}
6. Conclusion
This article discussed the overview of interfaces and abstract
classes and the key differences between them. Also, we examined
when to use each of them in our work to accomplish writing
flexible and clean code.
What is constructor and its uses? What is the difference between super and this?
Constructor is a special method that is used to initialize a newly created object and is
called just after the memory is allocated for the object. It can be used to initialize the objects
to desired values or default values at the time of object creation.
super() acts as immediate parent class constructor and should be first line in child class
constructor. this() acts as current class constructor and can be used in parametrized
constructors. When invoking a superclass version of an overridden method the super
keyword is used.
String model;
String color;
this.model=model;
this.color=color;
class Vehicle {
public Vehicle() {
public FourWheeler() {
public Car() {
System.out.println("I am a car");
Yes –
I am the super vehicle
I am a car or a truck or whatever 4 wheel has
I am a car
import java.io.*;
// Main class
class GFG {
// Returning instanceof
What are the access modifiers in java? Explain visibility of public, private, default and protractor?
As the name suggests access modifiers in Java helps to restrict the scope of
a class, constructor, variable, method, or data member. There are four types
of access modifiers available in java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
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?
Finalize method
It is a method that the Garbage Collector always calls just before the
deletion/destroying the object which is eligible for Garbage Collection, so as
to perform clean-up activity. Clean-up activity means closing the resources
associated with that object like Database Connection, Network Connection,
or we can say resource de-allocation. Remember, it is not a reserved
keyword. Once the finalize method completes immediately Garbage
Collector destroy that object. finalize method is present in Object class and
its syntax is:
protected void finalize throws Throwable{}
https://www.geeksforgeeks.org/g-fact-24-finalfinally-and-finalize-in-java/
String s1 = "true";
String s2 = "true";
//first sop
System.out.println(s1==s2);
String s3= new String("true");
//second sop
System.out.println(s1==s3);
//Third sop
System.out.println(s2==s4);
Output
true
false
false
str.trim();
System.out.println(str);
}
}
Output
hello
How many methods of String class have you used? Name them with example
Where are String values stored in memory? Why String class is immutable?
static blocks executes when class is loaded in java. instance block executes only
when instance of class is created, not called when class is loaded in java. this keyword
cannot be used in static blocks.
These variables are created when an These variables are created when a block,
object is instantiated and are method or constructor is started and the
accessible to all constructors, variable will be destroyed once it exits the
methods, or blocks in class. block, method, or constructor.
These variables are destroyed when These variables are destroyed when the
the object is destroyed. constructor or method is exited.
It can be accessed throughout the Its access is limited to the method in which it
Instance Variable Local Variable
class. is declared.
They are used to reserving memory They are used to decreasing dependencies
for data that the class needs and that between components I.e., the complexity of
too for the lifetime of the object. code is decreased.
It includes access modifiers such as It does not include any access modifiers such
private, public, protected, etc. as private, public, protected, etc.
What is the use of static variable? Can we use static variables inside non static methods? Can we use
non static variables inside static methods? How to invoke static methods?
Static variables are used to keep track of information that relates logically to an entire
class, as opposed to information that varies from instance to instance.
Yes, a non-static method can access a static variable or call a static method in Java.
In the static method, the method can only access only static data members and static
methods of another class or same class but cannot access non-static methods and
variables
Int i=0;
for(;i<10; i++){
System.out.println(i);
}
Yes, Prints from 1 to 9
The break statement is used to terminate the loop immediately. The continue
statement is used to skip the current iteration of the loop. break keyword is used to
indicate break statements in java programming. continue keyword is used to indicate
continue statement in java programming.
while do-while
while loop is entry controlled loop. do-while loop is exit controlled loop.
while(condition) do { statement(s); }
{ statement(s); } while(condition);
What will happen if we don’t have break statement inside matching catch? Should default be the
last statement in a switch case block?
Break will return control out of switch case.so if we don't use it then next case
statements will be executed until break appears. The break statement will stop the process
inside the switch.
The default statement is optional and can appear anywhere inside the switch block
Can your switch statement accept long, double or float data type?
The switch statement doesn't accept arguments of type long, float, double,boolean or
any object besides String.
What is the hierarchy of throwable class? What are checked and unchecked exceptions?
Checked Exceptions
These are the exceptions that are checked at compile time. If some code
within a method throws a checked exception, then the method must either
handle the exception or it must specify the exception using
the throws keyword. In checked exception, there are two types: fully checked
and partially checked exceptions. A fully checked exception is a checked
exception where all its child classes are also checked, like IOException,
InterruptedException. A partially checked exception is a checked exception
where some of its child classes are unchecked, like Exception.
For example, consider the following Java program that opens the file at
location “C:\test\a.txt” and prints the first three lines of it. The program
doesn’t compile, because the function main() uses FileReader() and
FileReader() throws a checked exception FileNotFoundException. It also
uses readLine() and close() methods, and these methods also throw
checked exception IOException
Unchecked Exceptions
These are the exceptions that are not checked at compile time. In C++, all
exceptions are unchecked, so it is not forced by the compiler to either handle
or specify the exception. It is up to the programmers to be civilized, and
specify or catch the exceptions. In Java, exceptions
under Error and RuntimeException classes are unchecked exceptions,
everything else under throwable is checked.
Consider the following Java program. It compiles fine, but it
throws ArithmeticException when run. The compiler allows it to compile
because ArithmeticException is an unchecked exception.
The error indicates trouble that primarily occurs due to the scarcity of system
resources. The exceptions are the issues that can appear at runtime and compile
time.
The throw keyword is used to throw an exception explicitly. It can throw only one
exception at a time. The throws keyword can be used to declare multiple exceptions,
separated by a comma. Whichever exception occurs, if matched with the declared ones, is
thrown automatically then.
import java.io.*;
import java.util.*;
Yes, It is possible to have a try block without a catch block by using a final block. As
we know, a final block will always execute even there is an exception occurred in a try block,
except System. exit() it will execute always.
try {
}catch(IOException e) {
}catch(FileNotFoundException e) {
}
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for
IOException
1 boolean false
2 int 0
S. No. Datatype Default Value
3 double 0.0
4 String null
What are the ways to make objects eligible for garbage collection?
public class GC {
gc1 = null;
Read
A marker interface is an interface that has no methods or constants inside it. 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
geeksforgeeks.org/multithreading-in-java/
1. If we extend the Thread class, our class cannot extend any other
class because Java doesn’t support multiple inheritance. But, if we
implement the Runnable interface, our class can still extend other
base classes.
2. We can achieve basic functionality of a thread by extending Thread
class because it provides some inbuilt methods like yield(),
interrupt() etc. that are not available in Runnable interface.
3. Using runnable will give you an object that can be shared amongst
multiple threads.
How to get today’s date using date class? How to add days in today’s date?
https://www.geeksforgeeks.org/collection-vs-collections-in-java-with-example/
Collection: Collection is a interface present in java.util.package. It is used to
represent a group of individual objects as a single unit. It is similar to the
container in the C++ language. The collection is considered as the root
interface of the collection framework. It provides several classes and
interfaces to represent a group of individual objects as a single unit.
The List, Set, and Queue are the main sub-interfaces of the collection
interface. The map interface is also part of the java collection framework, but
it doesn’t inherit the collection of the interface.
The add(), remove(), clear(), size(), and contains() are the important
methods of the Collection interface.
Declaration:
public interface Collection<E> extends Iterable<E>
Java
import java.io.*;
import java.util.*;
class GFG {
}
}
Output
Elements of arrlist before the operations:
[geeks, for, geeks]
Elements of arrlist after the operations:
[geeks, for, geeks, web, site]
[for, geeks, geeks, site, web]
https://www.geeksforgeeks.org/collections-in-java-2/
What is the difference between ArrayList and LinkedList? Which one is faster in insertion, deletion
and random access memory?
https://www.geeksforgeeks.org/arraylist-vs-linkedlist-java/
What is the difference between singly linkedlist, doubly linkedlist and circular linkedlist?
https://www.geeksforgeeks.org/difference-between-singly-linked-list-and-doubly-linked-list/
https://www.geeksforgeeks.org/difference-between-stack-and-queue-data-structures/
https://www.geeksforgeeks.org/difference-between-list-and-set-in-java/
What is HashMap?
https://www.geeksforgeeks.org/java-util-hashmap-in-java-with-examples/#:~:text=HashMap
%20is,type%20(e.g.%20an%20Integer).
https://www.geeksforgeeks.org/program-to-convert-set-to-list-in-java/
https://www.geeksforgeeks.org/how-to-iterate-hashset-in-java/#:~:text=First%2C%20we%20make
%20an%20iterator,Next()%20method%20in%20Java.
https://www.geeksforgeeks.org/iterate-map-java/
https://www.geeksforgeeks.org/sortedmap-java-examples/
https://www.geeksforgeeks.org/sortedset-java-examples/
https://www.geeksforgeeks.org/linkedhashmap-and-linkedhashset-in-java/#:~:text=LinkedHashMap
%20replaces%20the%20value%20with,things%20with%20one%20null%20value.
https://www.geeksforgeeks.org/difference-between-treemap-and-treeset-in-java/#:~:text=TreeSet
%20implements%20SortedSet%20in%20Java,one%20Key%20and%20one%20value.
https://www.geeksforgeeks.org/differences-between-hashmap-and-hashtable-in-java/
Can you iterate list forward and backward? Can you iterate linkedlist forward and backward?
1. class PalindromeExample{
2. public static void main(String args[]){
3. int r,sum=0,temp;
4. int n=454;//It is the number variable to be checked for palindrome
5.
6. temp=n;
7. while(n>0){
8. r=n%10; //getting remainder
9. sum=(sum*10)+r;
10. n=n/10;
11. }
12. if(temp==sum)
13. System.out.println("palindrome number ");
14. else
15. System.out.println("not palindrome");
16. }
17. }
import java.io.*;
import java.util.Scanner;
class GFG {
char ch;
https://www.geeksforgeeks.org/java-program-to-sort-the-elements-of-an-array-in-ascending-order/
https://www.geeksforgeeks.org/program-find-minimum-maximum-element-array/
https://www.geeksforgeeks.org/java-program-to-find-sum-of-array-elements/
https://www.geeksforgeeks.org/find-the-missing-number/
WAP to find largest and second largest in array? Smallest and second smallest in array?
https://www.geeksforgeeks.org/find-second-largest-element-array/
What are waits in selenium? Difference between implicit wait and explicit wait?
What are the challenges you faced in automation? What are the challenges you faced while working
with IE browser?
How to read data from excel? Difference between HSSFWorkbook and XSSFWorkbook?
How to read data from dynamic web table? How to fetch data from last raw of dynamic web table?
https://www.guru99.com/handling-dynamic-selenium-webdriver.html
int
lastRowcount=driver.findElement(By.xpath("//table[1]/tbody/")).findElements(By.tagNam
e("tr")).size();
WebElement Lastrow
=driver.findElement(By.xpath("//table[1]/tbody/tr["+lastRowcount+"]"));
In first Line we get the Last Row count from the table.
How to handle multiple windows in Selenium? How to open a new window? How do you switch
from one window to another window?
driver.get("https://www.selenium.dev/");
// A new window is opened and switches to it
driver.switchTo().newWindow(WindowType.WINDOW);
// Loads Sauce Labs open source website in the newly opened window
driver.get("https://opensource.saucelabs.com/");
driver.get("https://www.selenium.dev/");
// A new tab is opened and switches to it
driver.switchTo().newWindow(WindowType.TAB);
// Loads Sauce Labs open source website in the newly opened window
driver.get("https://opensource.saucelabs.com/");
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
driver.manage().window().maximize();
driver.get("http://www.naukri.com/");
String parent=driver.getWindowHandle();
Set<String>s=driver.getWindowHandles();
String child_window=I1.next();
if(!parent.equals(child_window))
driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());
driver.close();
driver.switchTo().window(parent);
How do you handle Alert? Can you write a method to check if alert exists?
driver.switchTo().alert().dismiss();
driver.switchTo().alert().accept();
driver.switchTo().alert().getText();
driver.switchTo().alert().sendKeys("Text");
selectByIndex
selectByValue
selectByVisibleText
Action
driver.get("URL of target website or webpage"); // Define the URL of the target website.
act.doubleClick(ele).perform();
Actions.dragAndDrop(Sourcelocator, Destinationlocator)
robot.mouseMove(400.5); // Navigating through mouse hover. Note that the coordinates might
differ, kindly check the coordinates of x and y axis and update it accordingly.
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
Thread.sleep(2000);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
Thread.sleep(2000);
These are just commonly asked or most asked questions. But trust me, if you prepare these
questions then obviously you will get good understanding of Java and Selenium to rock the
interview. All the best for your job hunting. 😊