0% found this document useful (0 votes)
4 views64 pages

Java Questions

The document discusses Java's primitive data types and wrapper classes, explaining the need for objects in methods and data structures. It covers concepts such as class loaders, immutability, OOP principles, method overloading and overriding, and the Object class's significance. Additionally, it highlights the differences between primitive types and their corresponding wrapper classes, emphasizing the flexibility and functionality provided by wrapper classes.

Uploaded by

sindhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views64 pages

Java Questions

The document discusses Java's primitive data types and wrapper classes, explaining the need for objects in methods and data structures. It covers concepts such as class loaders, immutability, OOP principles, method overloading and overriding, and the Object class's significance. Additionally, it highlights the differences between primitive types and their corresponding wrapper classes, emphasizing the flexibility and functionality provided by wrapper classes.

Uploaded by

sindhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

They convert primitive data types into objects.

Objects are needed if we wish to modify the


arguments passed into a method (because primitive types are passed by value).

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.

An object is needed to support synchronization in multithreading.What is Bytecode? What is JDK,


JVM, JRE?

What is the role of ClassLoader in Java?

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.

Can you save a java file without name?

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.

Autoboxing is a procedure of converting a primitive value into an object of the corresponding


wrapper class. For example, converting int to Integer class

. The Java compiler applies autoboxing when a primitive value is:

Passed as a parameter to a method that expects an object of the corresponding wrapper class.

Assigned to a variable of the corresponding wrapper class.

Unboxing is a procedure of converting an object of a wrapper type to its corresponding primitive


value. For example conversion of Integer to int. The Java compiler applies to unbox when an object
of a wrapper class is:
Passed as a parameter to a method that expects a value of the corresponding primitive type.

Assigned to a variable of the corresponding primitive type.

In Java, int is a primitive data type while Integer is a 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");

Important Points of Differences :

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.

// Java program to illustrate

// difference between

// int and Integer


public class Main {

public static void main(String args[])

Integer a = new Integer("123");

// Casting not possible

// int a = (int)"123";

// Casting not possible

// int c="123";

// Casting possible using methods

// from Integer Wrapper class

int b = Integer.parseInt("123");

System.out.print(a + new Float("10.1"));

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.

// Java program to illustrate

// difference between

// int and Integer

public class Main {

public static void main(String args[])

String bin = Integer.toBinaryString(123);

String oct = Integer.toOctalString(123);


String hex = Integer.toHexString(123);

System.out.print(bin + "\n" + oct + "\n" + hex);

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.

// Java program to illustrate

// difference between

// int and Integer

public class Main {

public static void main(String args[])

// mainethods convert integer to its binary form,

// apply the desired operation

// and then returns the decimal form

// of the newly formed binary number

// (12)10->(1100)2 ->

// rotate left by 2 units -> (110000)2->(48)10

int rL = Integer.rotateLeft(12, 2);

// (12)10->(1100)2 ->

// rotate right by 2 units -> (0011)2->(3)10

int rR = Integer.rotateRight(12, 2);

//(12)10 -> (00000000000000000000000000001100)2


// -> reverse ->(00110000000000000000000000000000)2

// -> (805306368)10

// int is of 32 bits

int rev = Integer.reverse(12);

System.out.print("Left Rotate : " + rL

+ "\nRight rotate : " + rR + "\nReverse : " + rev);

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.

// Java program to illustrate

// auto-boxing

import java.util.function.Function;

import java.util.function.Function;

public class Main {

public static void main(String args[])

Integer a = new Integer("12");

Integer d = new Integer("13");

int b = 2;
double c = 3.1;

Double f = new Double("12.1");

int d2 = a + d;

System.out.println("Sum of 2 Integer objects :"

+ (a + d));

System.out.println("Sum of an Integer object

and int value :" + (a + b));

System.out.println("Sum of an Integer object

and double value :" + (a + c));

System.out.println("Sum of an Integer object

and Double object :" + (a + f));

Output:

Sum of 2 Integer objects :25

Sum of an Integer object and int value :14

Sum of an Integer object and double value :15.1

Sum of an Integer object and Double object :24.1

Besides Integer, we have more wrapper classes in Java corresponding to the data types. These are
given as follows :

Equivalent wrapper classes of primitive types in Java

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?

Object-oriented programming has four basic concepts: encapsulation, abstraction,


inheritance and polymorphism.

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();

WebDriver itself is an Interface. So based on the above


statement WebDriver driver = new FirefoxDriver(); we are
initializing Firefox browser using Selenium WebDriver. It means we
are creating a reference variable (driver) of the interface
(WebDriver) and creating an Object. Here WebDriver is
an Interface as mentioned earlier and FirefoxDriver is a class.

An interface in Java looks similar to a class but both the interface


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

INHERITANCE
The mechanism in Java by which one class acquires the properties
(instance variables) and functionalities of another class is known as
Inheritance.

We create a Base Class in the Automation Framework to initialize


WebDriver interface, WebDriver waits, Property files, Excels, etc., in
the Base Class.

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.

Combination of overloading and overriding is known as


Polymorphism. We will see both overloading and overriding below.

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.,

Action class in TestNG is also an example of overloading.

Assert class in TestNG is also an example of overloading.

A class having multiple methods with same name but different


parameters is called Method Overloading

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.

Encapsulation is a mechanism of binding code and data (variables)


together in a single unit.

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.

1. toString() method returns the String representation of an Object. The


default implementation of toString() for an object returns the
HashCode value of the Object. We'll come to what HashCode is.
Overriding the toString() is straightforward and helps us print the
content of the Object. @ToString annotation from Lombok does that
for us. It Prints the class name and each field in the class with its
value. The @ToString annotation also takes in configuration keys
for various behaviours. Read here. callSuper just denotes that an
extended class needs to call the toString() from its
parent. hashCode() for an object returns an integer value, generated
by a hashing algorithm. This can be used to identify whether two
objects have similar Hash values which eventually help identifying
whether two variables are pointing to the same instance of the
Object. If two objects are equal from the .equals() method, they
must share the same HashCode
2. They are supposed to be defined on the entity, if at all you need to
override them.
3. Each of the three have their own
purposes. equals() and hashCode() are majorly used to identify
whether two objects are the same/equal. Whereas, toString() is used
to Serialise the object to make it more readable in logs.

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:

Method Overloading Method Overriding

Method overloading is a compile-time Method overriding is a run-time


polymorphism. polymorphism.

It is used to grant the specific


implementation of the method which is
It helps to increase the readability of the already provided by its parent class or
program. superclass.

It is performed in two classes with


It occurs within the class. inheritance relationships.

Method overloading may or may not Method overriding always needs


require inheritance. inheritance.

In method overloading, methods must


have the same name and different In method overriding, methods must have
signatures. the same name and same signature.

In method overloading, the return type


can or can not be the same, but we just In method overriding, the return type
have to change the parameter. must be the same or co-variant.

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.

It gives better performance. The reason


behind this is that the binding of
overridden methods is being done at
runtime. Poor performance

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.

Example of Method Overloading:


 Java

import java.io.*;

class MethodOverloadingEx {

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

public static void main(String args[])


{
System.out.println("add() with 2 parameters");
System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");


System.out.println(add(4, 6, 7));
}
}

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.");
}
}

class Dog extends Animal {

void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}
}

class MethodOverridingEx {

public static void main(String args[])


{
Dog d1 = new Dog();
Animal a1 = new Animal();

d1.eat();
a1.eat();

Animal animal = new Dog();


// eat() method of animal class is overridden by
// base class eat()
animal.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:

1. Upcasting: Upcasting is the typecasting of a child object to a


parent object. Upcasting can be done implicitly. Upcasting gives
us the flexibility to access the parent class members but it is not
possible to access all the child class members using this feature.
Instead of all the members, we can access some specified
members of the child class. For instance, we can access the
overridden methods.
2. Downcasting: Similarly, downcasting means the typecasting of
a parent object to a child object. Downcasting cannot be implicit.
The following image illustrates the concept of upcasting and downcasting:
Example: Let there be a parent class. There can be many children of a
parent. Let’s take one of the children into consideration. The child inherits the
properties of the parent. Therefore, there is an “is-a” relationship between
the child and parent. Therefore, the child can be implicitly upcasted to the
parent. However, a parent may or may not inherits the child’s properties.
However, we can forcefully cast a parent to a child which is known
as downcasting. After we define this type of casting explicitly, the compiler
checks in the background if this type of casting is possible or not. If it’s not
possible, the compiler throws a ClassCastException.
Let’s understand the following code to understand the difference:

 Java

// Java program to demonstrate


// Upcasting Vs Downcasting

// Parent class
class Parent {
String name;

// A method which prints the


// signature of the parent class
void method()
{
System.out.println("Method from Parent");
}
}

// Child class
class Child extends Parent {
int id;

// Overriding the parent method


// to print the signature of the
// child class
@Override void method()
{
System.out.println("Method from Child");
}
}

// Demo class to see the difference


// between upcasting and downcasting
public class GFG {

// Driver code
public static void main(String[] args)
{
// Upcasting
Parent p = new Child();
p.name = "GeeksforGeeks";

//Printing the parentclass name


System.out.println(p.name);
//parent class method is overriden method hence this
will be executed
p.method();

// Trying to Downcasting Implicitly


// Child c = new Parent(); - > compile time error

// 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:

From the above example we can observe the following points:

1. Syntax of Upcasting:

Parent p = new Child();


1. Upcasting will be done internally and due to upcasting the object is
allowed to access only parent class members and child class
specified members (overridden methods, etc.) but not all members.

// This variable is not


// accessible
p.id = 1;
1. Syntax of Downcasting:

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?

1. private and final methods can be overloaded but they


cannot be overridden. It means a class can have more
than one private/final methods of same name but a child
class cannot override the private/final methods of their
base class.

Not so important

1. Overloading happens at compile-time while Overriding


happens at runtime: The binding of overloaded method
call to its definition has happens at compile-time however
binding of overridden method call to its definition happens
at runtime.
2. Static methods can be overloaded which means a class
can have more than one static method of same name.
Static methods cannot be overridden, even if you declare
a same static method in child class it has nothing to do
with the same method of parent class.
3. The most basic difference is that overloading is being
done in the same class while for overriding base and child
classes are required. Overriding is all about giving a
specific implementation to the inherited method of parent
class.
4. Static binding is being used for overloaded methods
and dynamic binding is being used for
overridden/overriding methods.
5. Performance: Overloading gives better performance
compared to overriding. The reason is that the binding of
overridden methods is being done at runtime.
6. Return type of method does not matter in case of method
overloading, it can be same or different. However in case of
method overriding the overriding method can have more
specific return type (refer this).
7. Argument list should be different while doing method
overloading. Argument list should be same in method
Overriding

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

A method in a subclass is said to Override a method in its superclass if that


method has a signature identical to a method in its superclass. When this
method is called by an object of the subclass, then always the Overridden
version will be called. In other words, the method which was Overridden in
the superclass will become hidden.
The JVM has 2 choices, it can either call the original method present in the
superclass or the Overridden method present in the subclass. Due to late
binding, this decision is taken at run-time and not at compile-time.
Can We Override a Final Method?
No, the Methods that are declared as final cannot be Overridden or hidden.
For this very reason, a method must be declared as final only when we’re
sure that it is complete.
 It is noteworthy that abstract methods cannot be declared as final
because they aren’t complete and Overriding them is necessary.
 Methods are declared final in java to prevent subclasses from
Overriding them and changing their behavior, the reason this works
is discussed at the end of this article.
 The advantage of the final keyword is that it stops developers from
intentionally or unintentionally changing the behavior of methods
that should not be changed for security or other reasons.
Result of Overriding a Final Method
In the code below:
 The class IntegralOperations has two methods, add and subtract
that perform the expected operation.
 Both add and subtract are declared final.
 The class child extends IntegralOperations and tries to Override
add and subtract.
 Java

// Java Program to demonstrate result of overriding a final


// method

class IntegralOperations {

// add declared as final


final int add(int a, int b) { return a + b; }

// subtract declared as final


final int subtract(int a, int b) { return a - b; }
}

class child extends IntegralOperations {

// try to override add


@Override int add(int a, int b) { return a - b; }

// try to override subtract


@Override int subtract(int a, int b) { return a * b; }
}

public class Main {


public static void main(String[] args)
{
child c1 = new child();
System.out.println(c1.add(1, 4));
}
}

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.

Should return type be same in method overloading and overriding?

Return type of method does not matter in case of method


overloading, it can be same or different. However in case of method
overriding the overriding method can have more specific return type

Can a overriding method throw new or broader checked exception?

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.

Explain autoboxing in Java.

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.

// Java program to illustrate the Concept


// of Autoboxing and Unboxing

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an Integer Object


// with custom value say it be 10
Integer i = new Integer(10);

// Unboxing the Object


int i1 = i;

// 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?

Declaring a class abstract only means that you don't allow it to be


instantiated on its own.

Declaring a method abstract means that subclasses have to provide an


implementation for that method.

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.

As we know that abstraction refers to hiding the internal implementation of


the feature and only showing the functionality to the users. i.e. what it works
(showing), how it works (hiding). Both abstract class and interface are used
for abstraction, henceforth Interface and Abstract Class are required
prerequisites.

Abstract class vs Interface


Type of methods: Interface can have only abstract methods. An

abstract class can have abstract and non-abstract methods. From
Java 8, it can have default and static methods also.
 Final Variables: Variables declared in a Java interface are by
default final. An abstract class may 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.
 Accessibility of Data Members: Members of a Java interface are
public by default. A Java abstract class can have class members
like private, protected, etc.
Example 1-A:
 Java

// Java Program to Illustrate Concept of


// Abstract Class

// Importing required classes


import java.io.*;

// Class 1
// Helper abstract class
abstract class Shape {

// Declare fields
String objectName = " ";

// Constructor of this class


Shape(String name) { this.objectName = name; }

// 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);

// this keyword refers to current instance itself


this.length = length;
this.width = width;
}

// 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 {

// Main driver method


public static void main(String[] args)
{
// Creating the Object of Rectangle class
// and using shape class reference.
Shape rect = new Rectangle(2, 3, "Rectangle");

System.out.println("Area of rectangle: "


+ rect.area());

rect.moveTo(1, 2);

System.out.println(" ");

// Creating the Objects of circle class


Shape circle = new Circle(2, "Circle");

System.out.println("Area of circle: "


+ circle.area());

circle.moveTo(2, 4);
}
}

Output
Area of rectangle: 6.0
Rectangle has been moved to x = 1 and y = 2

Area of circle: 12.56


Circle has been moved to x = 2 and y = 4
What if we don’t have any common code between rectangle and circle then
go with the interface.

Example 1-B:
 Java

// Java Program to Illustrate Concept of Interface

// Importing I/O classes


import java.io.*;

// Interface
interface Shape {

// Abstract method
void draw();
double area();
}

// Class 1
// Helper class
class Rectangle implements Shape {

int length, width;

// constructor
Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}

@Override public void draw()


{
System.out.println("Rectangle has been drawn ");
}

@Override public double area()


{
return (double)(length * width);
}
}

// Class 2
// Helper class
class Circle implements Shape {
double pi = 3.14;
int radius;

// constructor
Circle(int radius) { this.radius = radius; }

@Override public void draw()


{
System.out.println("Circle has been drawn ");
}

@Override public double area()


{

return (double)((pi * radius * radius));


}
}

// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating the Object of Rectangle class
// and using shape interface reference.
Shape rect = new Rectangle(2, 3);

System.out.println("Area of rectangle: "


+ rect.area());

// Creating the Objects of circle class


Shape circle = new Circle(2);

System.out.println("Area of circle: "


+ circle.area());
}
}

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.

2. Class vs. Interface


First, let's look at the differences between a normal concrete class
vs. an interface.
A class is a user-defined type that acts as a blueprint for object
creation. It can have properties and methods that represent the
states and behaviors of an object, respectively.
An interface is also a user-defined type that is syntactically similar
to a class. It can have a collection of field constants and method
signatures that will be overridden by interface implementing
classes.
In addition to these, Java 8 new features support static and
default methods in interfaces to support backward compatibility.
Methods in an interface are implicitly abstract if they are
not static or default and all are public.
However, starting with Java 9, we can also add private methods in
interfaces.

3. Interface vs. Abstract Class


An abstract class is nothing but a class that is declared using
the abstract keyword. It also allows us to declare method
signatures using the abstract keyword (abstract method) and
forces its subclasses to implement all the declared methods.
Suppose if a class has a method that is abstract, then the class
itself must be abstract.
Abstract classes have no restrictions on field and method
modifiers, while in an interface, all are public by default. We can
have instance and static initialization blocks in an abstract class,
whereas we can never have them in the interface. Abstract
classes may also have constructors which will get executed
during the child object's instantiation.
Java 8 introduced functional interfaces, an interface with a
restriction of no more than one declared abstract method. Any
interface with a single abstract method other than static and
default methods is considered a functional interface. We can use
this feature to restrict the number of abstract methods to be
declared. While in abstract classes, we can never have this
restriction on the number of abstract methods declaration.
Abstract classes are analogous to interfaces in some ways:

 We can't instantiate either of them. i.e., we cannot use


the statement new TypeName() directly to instantiate an
object. If we used the aforementioned statement, we have to
override all the methods using an anonymous class
 They both might contain a set of methods declared
and defined with or without their implementation. i.e.,
static & default methods(defined) in an interface, instance
methods(defined) in abstract class, abstract
methods(declared) in both of them

4. When to Use an Interface


Let's look at some scenarios when one should go with an
interface:

 If the problem needs to be solved using multiple


inheritances and is composed of different class hierarchies
 When unrelated classes implement our interface. For
example, Comparable provides the compareTo() method
that can be overridden to compare two objects
 When application functionalities have to be defined as a
contract, but not concerned about who implements the
behavior. i.e., third-party vendors need to implement it fully

Consider using the interface when our problem makes the


statement “A is capable of [doing this]”. For example,
“Clonable is capable of cloning an object”, “Drawable is capable
of drawing a shape”, etc.
Let us consider an example that makes use of an interface:
public interface Sender {
void send(File fileToBeSent);
}
public class ImageSender implements Sender {
@Override
public void send(File fileToBeSent) {
// image sending implementation code.
}
}
Here, Sender is an interface with a method send(). Hence,
“Sender is capable of sending a file” we implemented it as an
interface. ImageSender implements the interface for sending an
image to the target. We can further use the above interface to
implement VideoSender, DocumentSender to accomplish various
jobs.
Consider a unit test case the makes use of the above interface
and its implemented class:
@Test
void givenImageUploaded_whenButtonClicked_thenSendImage() {

File imageFile = new File(IMAGE_FILE_PATH);


Sender sender = new ImageSender();
sender.send(imageFile);
}

5. When to Use an Abstract Class


Now, let's see some scenarios when one should use the abstract
class:

 When trying to use the inheritance concept in code (share


code among many related classes), by providing common
base class methods that the subclasses override
 If we have specified requirements and only partial
implementation details
 While classes that extend abstract classes have several
common fields or methods (that require non-public
modifiers)
 If one wants to have non-final or non-static methods to
modify the states of an object

Consider using abstract classes and inheritance when our


problem makes the evidence “A is a B”. For example, “Dog is
an Animal”, “Lamborghini is a Car”, etc.
Let's look at an example that uses the abstract class:
public abstract class Vehicle {

protected abstract void start();


protected abstract void stop();
protected abstract void drive();
protected abstract void changeGear();
protected abstract void reverse();

// standard getters and setters


}
public class Car extends Vehicle {

@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() {

Vehicle car = new Car("BMW");

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.

Will this code compile?

//No but will compile if the constructor has arguments

public class Vehicle {

String model;

String color;

public Vehicle(String model, String color) {

this.model=model;

this.color=color;

public static void main(String[] args) {

Vehicle v = new Vehicle();

What will be the output of below code?

class Vehicle {

public Vehicle() {

System.out.println("I am the super vehicle");


}

class FourWheeler extends Vehicle {

public FourWheeler() {

System.out.println("I am a car or a truck or whatever 4 wheel has");

class Car extends FourWheeler{

public Car() {

System.out.println("I am a car");

public class Demo{

public static void main(String[] args) {

Car c = new Car();

Yes –
I am the super vehicle
I am a car or a truck or whatever 4 wheel has
I am a car

What is the use of instanceof operator in java?

instanceof is a keyword that is used for checking if a reference variable is


containing a given type of object reference or not. Following is a Java
program to show different behaviors of instanceof. Henceforth it is known as
a comparison operator where the instance is getting compared
to type returning boolean true or false as in java we do not have 0 and 1
boolean return types.
// Java Program to Illustrate instanceof Keyword
// Importing required I/O classes

import java.io.*;

// Main class

class GFG {

public static void main(String[] args)

// Creating object of class inside main()

GFG object = new GFG();

// Returning instanceof

System.out.println(object instanceof GFG);

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?

1. Child c = new Child(): The use of this initialization is to access all


the members present in both parent and child classes, as we are
inheriting the properties.
2. Parent p = new Child(): This type of initialization is used to access
only the members present in the parent class and the methods
which are overridden in the child class. This is because the parent
class is upcasted to the child class.

What is the use of final keyword in a variable, method and class?

Java final keyword is a non-access specifier that is used to


restrict a class, variable, and method. If we initialize a variable
with the final keyword, then we cannot modify its value.

If we declare a method as final, then it cannot be overridden by


any subclasses. And, if we declare a class as final, we restrict the
other classes to inherit or extend it.
Difference between final, finally and finalize?

final (lowercase) is a reserved keyword in java. We can’t use it as an


identifier, as it is reserved. We can use this keyword with variables, methods
and also with classes. The final keyword in java has different meaning
depending upon it is applied to variable, class or method.
final with Variables : The value of variable cannot be changed once
initialized.
If we declare any variable as final, we can’t modify its contents since it is
final, and if we modify it then we get Compile Time Error.
final with Class : The class cannot be subclassed. Whenever we declare
any class as final, it means that we can’t extend that class or that class can’t
be extended, or we can’t make a subclass of that class.
final with Method : The method cannot be overridden by a subclass.
Whenever we declare any method as final, then it means that we can’t
override that method.
finally keyword
Just as final is a reserved keyword, so in the same way finally is also a
reserved keyword in java i.e, we can’t use it as an identifier. The finally
keyword is used in association with a try/catch block and guarantees that a
section of code will be executed, even if an exception is thrown. The finally
block will be executed after the try and catch blocks, but before control
transfers back to its origin.

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/

What is the difference between == and equal()?


Both equals() method and the == operator are used to compare two objects
in Java. == is an operator and equals() is method. But == operator compares
reference or memory location of objects in a heap, whether they point to the
same location or not.
Whenever we create an object using the operator new, it will create a new
memory location for that object. So we use the == operator to check memory
location or address of two objects are the same or not.
In general, both equals() and “==” operators in Java are used to compare
objects to check equality, but here are some of the differences between the
two:
1. The main difference between the .equals() method and == operator
is that one is a method, and the other is the operator.
2. We can use == operators for reference comparison (address
comparison) and .equals() method for content comparison. In
simple words, == checks if both objects point to the same memory
location whereas .equals() evaluates to the comparison of values in
the objects.
3. If a class does not override the equals method , then by default, it
uses the equals(Object o) method of the closest parent class that
has overridden this method. See Why to Override equals(Object)
and hashCode() method ? in detail.

What will be the output of below code?

public class StringExample {

public static void main(String[] args) {

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);

String s4= "True";

//Third sop

System.out.println(s2==s4);

Output
true
false
false

What will be the output of below code?

public class StringExample {

public static void main(String[] args) {

String str = " hello ";

str.trim();

System.out.println(str);

}
}

Output
hello

How many methods of String class have you used? Name them with example

What is the difference between String, Stringbuffer and Stringbuilder?

String is immutable whereas StringBuffer and StringBuilder are mutable classes.


StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why
StringBuilder is faster than StringBuffer. String concatenation operator (+) internally uses
StringBuffer or StringBuilder class.

Where are String values stored in memory? Why String class is immutable?

What is static block and instance block?

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.

What is the default value of instance variable and local variable?

Instance Variable Local Variable

They are defined as a type of variable


They are defined in class but outside declared within programming blocks or
the body of methods. subroutines.

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.

These variables do not always have some


These variables are given a default value, so there must be a value assigned by
value if it is not assigned by code. code.

It is not compulsory to initialize It is important to initialize local variables


instance variables before use. before use.

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

Is it a valid for loop?

Int i=0;

for(;i<10; i++){

System.out.println(i);

}
Yes, Prints from 1 to 9

What is the difference between break and continue?

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.

What is the difference between while and do-while?

while do-while

Condition is checked first then Statement(s) is executed atleast


statement(s) is executed. once, thereafter condition is checked.

It might occur statement(s) is


executed zero times, If condition is At least once the statement(s) is
false. executed.

No semicolon at the end of while. Semicolon at the end of while.


while(condition) while(condition);

If there is a single statement,


brackets are not required. Brackets are always required.

Variable in condition is initialized variable may be initialized before or


before the execution of loop. within the loop.

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.

What is the difference between Error and 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.

both Errors and Exceptions are the subclasses of java.lang.Throwable


class. Error refers to an illegal operation performed by the user which results
in the abnormal working of the program. Programming errors often remain
undetected until the program is compiled or executed. Some of the errors
inhibit the program from getting compiled or executed. Thus errors should be
removed before compiling and executing. It is of three types:
 Compile-time
 Run-time
 Logical
Whereas exceptions in java refer to an unwanted or unexpected event, which
occurs during the execution of a program i.e at run time, that disrupts the
normal flow of the program’s instructions.

What is the difference between throw and throws?

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.

public class GFG {


public static void main(String[] args)
{
// Use of unchecked Exception
try {
// double x=3/0;
throw new ArithmeticException();
}
catch (ArithmeticException e) {
e.printStackTrace();
}
}
}

import java.io.*;
import java.util.*;

public class GFG {

public static void writeToFile() throws Exception


{
BufferedWriter bw = new BufferedWriter(
new FileWriter("myFile.txt"));
bw.write("Test");
bw.close();
}

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


{
try {
writeToFile();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

Is try block without finally and catch allowed?

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.

How to handle multi level exceptions?


A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Will this code compile?

public class ExceptionExample {

public static void main(String[] args) {

try {

FileReader f = new FileReader(new File("D:\\myfile"));

}catch(IOException e) {

}catch(FileNotFoundException e) {

}
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for
IOException

If the otherway around File not found exception will be displayed

What are the default values of array?

S. No. Datatype Default Value

1 boolean false

2 int 0
S. No. Datatype Default Value

3 double 0.0

4 String null

5 User-Defined Type null

What is garbage collection?

How to run garbage collection? When will it run?

What are the ways to make objects eligible for garbage collection?

How many objects available for GC?

public class GC {

public static void main(String[] args) {

GC gc1= new GC();

GC gc2 = new GC();


GC gc3 = new GC();

gc1 = null;

Difference between System.gc() and Runtime.getRuntime().gc()?

How do you read contents of a file? How do you write in a file?


Path file = null;
if ("API".equalsIgnoreCase(framework)) {
file = Paths.get(config.getProperty("lastTimestampAPI"));
} else {
file =
Paths.get(config.getProperty("lastTimestampSHTA"));
} /*
* else { // This logic need to confirm with Prashant }
*/
// if file doesnt exists, then create it
List<String> lstLines = new ArrayList<String>();
lstLines.add("" + latestTimeStamp);
if (!file.getParent().toFile().exists()) {
file.getParent().toFile().mkdirs();
}
Files.write(file, lstLines, StandardCharsets.UTF_8);

Read

Path file = null;


if ("API".equals(framework)) {
file = Paths.get(config.getProperty("lastTimestampAPI"));
} else {
file =
Paths.get(config.getProperty("lastTimestampSHTA"));
}
// if file doesnt exists, then create it
if (file.toFile().exists()) {
List<String> lines = Files.readAllLines(file,
StandardCharsets.UTF_8);
return lines.get(0);
}
What is functional interface? Give example of functional interfaces in Java?

A functional interface is an interface that contains only one abstract


method. They can have only one functionality to exhibit. From Java 8
onwards, lambda expressions can be used to represent the instance of a
functional interface. A functional interface can have any number of default
methods. Runnable, ActionListener, Comparable are some of the
examples of functional interfaces.
class Test {
public static void main(String args[])
{

// lambda expression to create the object


new Thread(() -> {
System.out.println("New thread created");
}).start();
}
}
 Runnable –> This interface only contains the run() method.
 Comparable –> This interface only contains the compareTo()
method.
 ActionListener –> This interface only contains the
actionPerformed() method.
 Callable –> This interface only contains the call() method.

What are marker interfaces in Java?

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

What is multithreading? Difference between process and thread?

geeksforgeeks.org/multithreading-in-java/

Multithreading is a Java feature that allows concurrent execution of two or


more parts of a program for maximum utilization of CPU. Each part of such
program is called a thread. So, threads are light-weight processes within a
process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
What is the difference between thread class and runnable interface?

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?

How to get current month and year using calendar class?

What is stream in Java 8?

What is default and static methods in interface in Java 8?

What is the difference between Collections and Collection?

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>

Type Parameters: E - the type of elements returned by this


iterator
Collections: Collections is a utility class present in java.util.package. It
defines several utility methods like sorting and searching which is used to
operate on collection. It has all static methods. These methods provide
much-needed convenience to developers, allowing them to effectively work
with Collection Framework . For example, It has a method sort() to sort the
collection elements according to default sorting order, and it has a
method min(), and max() to find the minimum and maximum value
respectively in the collection elements.
Declaration:
public class Collections extends Object
Collection vs Collections:
Collection Collections

It is an interface. It is a utility class.

It is used to represent a group of It defines several utility methods that are


individual objects as a single unit. used to operate on collection.

The Collection is an interface that


contains a static method since java8.
The Interface can also contain abstract
and default methods. It contains only static methods.

 Java

// Java program to demonstrate the difference


// between Collection and Collections

import java.io.*;
import java.util.*;

class GFG {

public static void main (String[] args)


{

// Creating an object of List<String>


List<String> arrlist = new ArrayList<String>();

// Adding elements to arrlist


arrlist.add("geeks");
arrlist.add("for");
arrlist.add("geeks");

// Printing the elements of arrlist


// before operations
System.out.println("Elements of arrlist before the
operations:");
System.out.println(arrlist);

System.out.println("Elements of arrlist after the


operations:");

// Adding all the specified elements


// to the specified collection
Collections.addAll(arrlist, "web", "site");

// Printing the arrlist after


// performing addAll() method
System.out.println(arrlist);

// Sorting all the elements of the


// specified collection according to
// default sorting order
Collections.sort(arrlist);

// Printing the arrlist after


// performing sort() method
System.out.println(arrlist);

}
}
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]

What is the hierarchy of collection?


What are the sub interfaces and sub classes of List, Set and Map interface?

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/

What main interfaces LinkedList implements?

What is the difference between Stack and Queue?

https://www.geeksforgeeks.org/difference-between-stack-and-queue-data-structures/

What is the difference between List and Set?

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).

How to convert Array into Arraylist and Arraylist into Array?


https://www.geeksforgeeks.org/conversion-of-array-to-arraylist-in-java/

How to convert Set into List?

https://www.geeksforgeeks.org/program-to-convert-set-to-list-in-java/

How to iterate HashSet and HashMap?

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/

What is SortedSet and SortedMap?

https://www.geeksforgeeks.org/sortedmap-java-examples/

https://www.geeksforgeeks.org/sortedset-java-examples/

What is LinkedHashSet and LinkedHashMap?

https://www.geeksforgeeks.org/linkedhashmap-and-linkedhashset-in-java/#:~:text=LinkedHashMap
%20replaces%20the%20value%20with,things%20with%20one%20null%20value.

What is TreeSet and TreeMap?

https://www.geeksforgeeks.org/difference-between-treemap-and-treeset-in-java/#:~:text=TreeSet
%20implements%20SortedSet%20in%20Java,one%20Key%20and%20one%20value.

What is the difference between HashTable and HashMap?

https://www.geeksforgeeks.org/differences-between-hashmap-and-hashtable-in-java/

What are difference methods of Collections class have you used?

Can you iterate list forward and backward? Can you iterate linkedlist forward and backward?

What is the between comparable and comparator?

Why can we compare Strings without implementing compare() or compareTo methods?


WAP to check if a given number in palindrome.

A palindrome number is a number that is same after reverse.

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. }

WAP to count duplicates in a given string.

1. public class DuplicateCharacters {


2. public static void main(String[] args) {
3. String string1 = "Great responsibility";
4. int count;
5.
6. //Converts given string into character array
7. char string[] = string1.toCharArray();
8.
9. System.out.println("Duplicate characters in a given string: ");
10. //Counts each character present in the string
11. for(int i = 0; i <string.length; i++) {
12. count = 1;
13. for(int j = i+1; j <string.length; j++) {
14. if(string[i] == string[j] && string[i] != ' ') {
15. count++;
16. //Set string[j] to 0 to avoid printing visited charact
er
17. string[j] = '0';
18. }
19. }
20. //A character is considered as duplicate if count is grea
ter than 1
21. if(count > 1 && string[i] != '0')
22. System.out.println(string[i]);
23. }
24. }
25. }

WAP to reverse a string using inbuilt reverse method as well as programmatically.

// java program to reverse a word

import java.io.*;

import java.util.Scanner;

class GFG {

public static void main (String[] args) {

String str= "Geeks", nstr="";

char ch;

System.out.print("Original word: ");

System.out.println("Geeks"); //Example word

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

ch= str.charAt(i); //extracts each character

nstr= ch+nstr; //adds each character in front of the existing string


}

System.out.println("Reversed word: "+ nstr);

WAP to sort an array.

https://www.geeksforgeeks.org/java-program-to-sort-the-elements-of-an-array-in-ascending-order/

WAP to find min and max in array.

https://www.geeksforgeeks.org/program-find-minimum-maximum-element-array/

WAP to find sum of array.

https://www.geeksforgeeks.org/java-program-to-find-sum-of-array-elements/

WAP to find missing number in array.

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/

Where have you used List, Set and Map in Selenium?

Example of Selenium methods using method overloading?

Can you name 10 interfaces in Selenium?

Have you ever designed framework? Please explain your framework.

What is WebDriver and WebElement?

What is the super interface of WebDriver? What is the hierarchy of WebDriver?

What are methods of WebDriver and WebElement?


What is the difference between findelement and findElements?

What are waits in selenium? Difference between implicit wait and explicit wait?

What is the importance of / and // in xpath?

What is the importance of *, $ and ^ in Css selector?

What are the challenges you faced in automation? What are the challenges you faced while working
with IE browser?

Explain Page factory model.

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;

public class WindowHandle_Demo {

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

System.setProperty("webdriver.chrome.driver","Path to the driver");

WebDriver driver = new ChromeDriver();

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

// Load the website

driver.get("http://www.naukri.com/");

// It will return the parent window name as a String

String parent=driver.getWindowHandle();

Set<String>s=driver.getWindowHandles();

// Now iterate using Iterator

Iterator<String> I1= s.iterator();


while(I1.hasNext())

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();

//switch to the parent window

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");

How do you handle frames in Selenium?


driver.switchTo().frame(0);
WebElement iframeElement = driver.findElement(By.id("IF1"));

//now use the switch command


driver.switchTo().frame(iframeElement);

Can you write isElementPresent method?

What are the various example of locator strategies in Selenium?

What is the difference between Xpath and CSS locators?

How to select values from dropdown?


Select select = new Select(WebElement webelement);

 selectByIndex
 selectByValue
 selectByVisibleText

What is the difference between Action and Actions?

Action

In Selenium, Action is an interface which represents a single user-interaction


action. It is defined in org.openqa.selenium.interactions. It contains one of the
most widely used method perform()
In Selenium, Actions is a Class. It is defined in org.openqa.selenium.interactions.
This is the user-facing API for emulating complex user gestures. Actions Class
implements the builder
How to do double click, right click, drag and drop?

driver.get("URL of target website or webpage"); // Define the URL of the target website.

Actions act = new Actions(driver);

//Double click on element


WebElement ele = driver.findElement(By.xpath("XPath of the element"));

act.doubleClick(ele).perform();

// Right click the button to launch right click menu options


Actions action = new Actions(driver);

WebElement link = driver.findElement(By.cssSelector(".context-menu-one"));


action.contextClick(link).perform();

Actions.dragAndDrop(Sourcelocator, Destinationlocator)

What is robot class? Where do you use in Selenium?

1. Robot Class can simulate Keyboard and Mouse Event


2. Robot Class can help in upload/download of files when using selenium
web driver
3. Robot Class can easily be integrated with current automation framework
(keyword, data-driven or hybrid)

Robot robot = new Robot();

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);

What is the difference between quit and close?

Can you explain about some common exceptions in Selenium?

What is JavaScriptExecutor in Selenium?


//By executing a java script
JavascriptExecutor exe = (JavascriptExecutor) driver;
Integer numberOfFrames =
Integer.parseInt(exe.executeScript("return window.length").toString());
System.out.println("Number of iframes on the page are "
+ numberOfFrames);
How do you do parallel execution? What is threadlocal?

What are the various ways of click and sendkeys in Selenium?

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. 😊

You might also like