Java Interview Questions - Q&A
Java Interview Questions - Q&A
Kus
JAVA INTERVIEW
QUESTIONS
@kushalparikh11
Kushalparikh1999@outlook.com
https://www.linkedin.com/in/kushalparikh11/
Kushal Parikh
QA Automation Engineer
@KUSHALPARIKH11 1
Kushal Parikh
QA Automation Engineer
the hardware. However, Java applications are typically more portable and secure
than C++ applications.
In general, Java is a good choice for developing portable, secure, and easy-to-
maintain applications. C++ is a good choice for developing high-performance
applications that require direct access to the operating system.
It’s an
It contains JRE + JVM follows three notations:
implementation of
development Specification, Implementation, and Runtime
the JVM which
tools. Instance.
physically exists.
• public: Public is an access modifier, which is used to specify who can access this
method. Public means that this Method will be accessible by any Class.
• static: It is a keyword in java which identifies it is class-based. main() is made static
in Java so that it can be accessed without creating the instance of a Class. In case,
main is not made static then the compiler will throw an error as main() is called
by the JVM before any objects are made and only static methods can be directly
invoked via the class.
• void: It is the return type of the method. Void defines the method which will not
return any value.
@KUSHALPARIKH11 2
Kushal Parikh
QA Automation Engineer
• main: It is the name of the method which is searched by JVM as a starting point
for an application with a particular signature only. It is the method where the main
execution occurs.
• String args[]: It is the parameter passed to the main method.
1. Bootstrap ClassLoader
2. Extension ClassLoader
3. System/Application ClassLoader
Java is not 100% Object-oriented because it makes use of eight primitive data
types such as boolean, byte, char, int, float, double, long, short which are not
objects.
1. Default Constructor: In Java, a default constructor is the one which does not take
any inputs. In other words, default constructors are the no argument constructors
which will be created by default in case you no other constructor is defined by the
user. Its main purpose is to initialize the instance variables with the default values.
Also, it is majorly used for object creation.
@KUSHALPARIKH11 3
Kushal Parikh
QA Automation Engineer
Q11. What is singleton class in Java and how can we make a class
singleton?
Singleton class is a class whose only one instance can be created at any given
time, in one JVM. A class can be made singleton by making its constructor
private.
Q12. What is the difference between Array list and vector in Java?
ArrayList Vector
Array List can only use Iterator for Vector can use both Enumeration and Iterator for
traversing an Array List. traversing.
Here’s an example Java program that takes a matrix as user input and rotates it
90 degrees clockwise:
1import java.util.Scanner;
2
3public class MatrixRotation {
4 public static void main(String[] args) {
@KUSHALPARIKH11 4
Kushal Parikh
QA Automation Engineer
33 }
34 System.out.println();
35 }
36 }
37
38 // Function to rotate the matrix 90 degrees clockwise
39 public static int[][] rotateMatrixClockwise(int[][] matrix) {
40 int rows = matrix.length;
@KUSHALPARIKH11 5
Kushal Parikh
QA Automation Engineer
Equals() method is defined in Object class in Java and used for checking equality
of two objects defined by business logic.
Here’s an example Java program that implements the binary search algorithm
using recursion:
@KUSHALPARIKH11 6
Kushal Parikh
QA Automation Engineer
26
27 if (arr[mid] == target) {
@KUSHALPARIKH11 7
Kushal Parikh
QA Automation Engineer
The `binarySearchRecursive` function takes the array, target value, and indices
for the low and high boundaries of the search range. It compares the target
value with the middle element of the current range. If they match, the function
returns the index. If the target is smaller, it recursively calls itself with the left
half of the range. If the target is larger, it recursively calls itself with the right half
of the range. The process continues until the element is found or the low index
becomes greater than the high index.
The program outputs the index where the element is found or a message
indicating that the element was not found in the array.
Note: The program assumes that the array is sorted in ascending order.
When you create a subclass instance, you’re also creating an instance of the
parent class, which is referenced to by the super reference variable.
@KUSHALPARIKH11 8
Kushal Parikh
QA Automation Engineer
It permits the null object. It does not allow the null object.
It is faster than TreeSet especially for It is slower than HashSet for these
search, insert, and delete operations. operations.
Q18. What are the differences between HashMap and HashTable in Java?
HashMap Hashtable
It is faster. It is slower.
@KUSHALPARIKH11 9
Kushal Parikh
QA Automation Engineer
Reflection is a runtime API for inspecting and changing the behavior of methods,
classes, and interfaces. Java Reflection is a powerful tool that can be really
beneficial. Java Reflection allows you to analyze classes, interfaces, fields, and
methods during runtime without knowing what they are called at compile time.
Reflection can also be used to create new objects, call methods, and get/set field
values. External, user-defined classes can be used by creating instances of
extensibility objects with their fully-qualified names. Debuggers can also use
reflection to examine private members of classes.
Yes, we can call a constructor of a class inside another constructor. This is also
called as constructor chaining. Constructor chaining can be done in 2 ways-
1. Within the same class: For constructors in the same class, the this() keyword
can be used.
2. From the base class: The super() keyword is used to call the constructor from
the base class.
The constructor chaining follows the process of inheritance. The constructor of
the sub class first calls the constructor of the super class. Due to this, the
creation of sub class’s object starts with the initialization of the data members of
the super class. The constructor chaining works similarly with any number of
classes. Every constructor keeps calling the chain till the top of the chain.
1import java.util.Scanner;
2
3public class StringReversal {
@KUSHALPARIKH11 10
Kushal Parikh
QA Automation Engineer
4
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7
8 // Get the string from the user
9 System.out.print("Enter a string: ");
10 String input = scanner.nextLine();
11
12 // Reverse the string
13
String reversedString = reverseString(input);
14
15
// Print the reversed string
16
System.out.println("Reversed string: " + reversedString);
17
}
18
19
// Function to reverse a string
20
public static String reverseString(String str) {
21
StringBuilder reversed = new StringBuilder(str);
22
reversed.reverse();
23
return reversed.toString();
24
}
25
}
This program prompts the user to enter a string. It then calls the `reverseString`
function to reverse the string using the `reverse()` method of the
`StringBuilder` class. The reversed string is then printed to the console.
Q23. Contiguous memory locations are usually used for storing actual
values in an array but not in ArrayList. Explain.
@KUSHALPARIKH11 11
Kushal Parikh
QA Automation Engineer
An array generally contains elements of the primitive data types such as int,
float, etc. In such cases, the array directly stores these elements at contiguous
memory locations. While an ArrayList does not contain primitive data types. An
arrayList contains the reference of the objects at different memory locations
instead of the object itself. That is why the objects are not stored at contiguous
memory locations.
Q24. How is the creation of a String using new() different from that of a
literal?
When we create a string using new(), a new object is created. Whereas, if we
create a string using the string literal syntax, it may return an already existing
object with the same name.
Java allows multiple threads to execute. They may be accessing the same
variable or object. Synchronization helps to execute threads one after another.
It is important as it helps to execute all concurrent threads while being in sync. It
prevents memory consistency errors due to access to shared memory. An
example of synchronization code is-
As we have synchronized this function, this thread can only use the object after
the previous thread has used it.
Double Brace Initialization is a Java term that refers to the combination of two
independent processes. There are two braces used in this. The first brace
creates an anonymous inner class. The second brace is an initialization block.
When these both are used together, it is known as Double Brace Initialization.
The inner class has a reference to the enclosing outer class, generally using the
‘this’ pointer. It is used to do both creation and initialization in a single
@KUSHALPARIKH11 12
Kushal Parikh
QA Automation Engineer
Q26. Why is it said that the length() method of String class doesn’t return
accurate results?
The length() method of String class doesn’t return accurate results because
it simply takes into account the number of characters within in the String. In
other words, code points outside of the BMP (Basic Multilingual Plane), that is,
code points having a value of U+10000 or above, will be ignored.
The reason for this is historical. One of Java’s original goals was to consider all
text as Unicode; yet, Unicode did not define code points outside of the BMP at
the time. It was too late to modify char by the time Unicode specified such code
points.
Q27. What are the differences between Heap and Stack Memory in Java?
• Instructor-led Sessions
• Real-life Case Studies
• Assignments
• Lifetime Access
Explore Curriculum
@KUSHALPARIKH11 13
Kushal Parikh
QA Automation Engineer
Stack memory is used only by one Heap memory is used by all the parts of
Memory
thread of execution. the application.
Stack memory can’t be accessed Objects stored in the heap are globally
Access
by other threads. accessible.
Exists until the end of execution of Heap memory lives from the start till the
Lifetime
the thread. end of application execution.
@KUSHALPARIKH11 14
Kushal Parikh
QA Automation Engineer
method has been compiled, the JVM summons the compiled code of that method
directly rather than interpreting it. This is why it is often responsible for the
performance optimization of Java applications at the run time.
1. Default
2. Private
3. Protected
4. Public
1class Abc {
2member variables // class body
3methods}
1. State
2. Behavior
@KUSHALPARIKH11 15
Kushal Parikh
QA Automation Engineer
3. Identity
Example
1if(x > 100)
2{
3String test = "Edureka";
4}
object of that class will create it’s own copy of the variable while using it. Thus, any
changes made to the variable won’t reflect in any other instances of that class and
will be bound to that particular instance only.
1class Test{
2public String EmpName;
3public int empAge;
4}
5. Method name may or may not be 5. Constructor name must always be the same
same as class name as the class name
• final variable
When the final keyword is used with a variable then its value can’t be changed
once assigned. In case the no value has been assigned to the final variable then
using only the class constructor a value can be assigned to it.
• final method
When a method is declared final then it can’t be overridden by the inheriting class.
• final class
When a class is declared as final in Java, it can’t be extended by any subclass class
but it can extend other class.
@KUSHALPARIKH11 17
Kushal Parikh
QA Automation Engineer
Example break:
Example continue:
@KUSHALPARIKH11 18
Kushal Parikh
QA Automation Engineer
For example:
this() super()
1. this() represents the current instance of 1. super() represents the current instance
a class of a parent/base class
2. Used to call the default constructor of 2. Used to call the default constructor of
the same class the parent/base class
3. Used to access methods of the current 3. Used to access methods of the base
class class
4. Used for pointing the current class 4. Used for pointing the superclass
instance instance
5. Must be the first line of a block 5. Must be the first line of a block
@KUSHALPARIKH11 19
Kushal Parikh
QA Automation Engineer
1. The static keyword must be used before the 1. No need to use the static keyword before
method name the method name
Constant String
Storage Area Heap Area Heap Area
Pool
@KUSHALPARIKH11 20
Kushal Parikh
QA Automation Engineer
If you think this article is helpful, you can check out Edureka’s Java Training in
Chennai as well.
Arrays can contain primitive data types as Arraylists can contain only objects, no primitive
well as objects data types are allowed
@KUSHALPARIKH11 21
Kushal Parikh
QA Automation Engineer
Q48. What is collection class in Java? List down its methods and interfaces.
In Java, the collection is a framework that acts as an architecture for storing and
manipulating a group of objects. Using Collections you can perform various tasks
like searching, sorting, insertion, manipulation, deletion, etc. Java collection
framework includes the following:
• Interfaces
• Classes
• Methods
The below image shows the complete hierarchy of the Java Collection.
@KUSHALPARIKH11 22
Kushal Parikh
QA Automation Engineer
types of polymorphism:
class Car {
1
void run()
2
{
3
System.out.println("Car is running");
4
}
5
}
6
class Audi extends Car {
7
8
void run()
9{
10System.out.prinltn("Audi is running safely at 100km/h");
11}
12public static void main(String args[])
13{
14Car b= new Audi(); //upcasting
@KUSHALPARIKH11 23
Kushal Parikh
QA Automation Engineer
15b.run();
16}
17}
An abstract class can have instance variables An Interface cannot have instance variables
@KUSHALPARIKH11 24
Kushal Parikh
QA Automation Engineer
If we add a new method to an abstract class If we add a new method to an Interface then we
then we have the option of providing default have to track down all the implementations of
implementation and therefore all the existing the interface and define implementation for the
code might work properly new method
Inheritance in Java is the concept where the properties of one class can be
inherited by the other. It helps to reuse the code and establish a relationship
between different classes. Inheritance is performed between two types of classes:
A class which inherits the properties is known as Child Class whereas a class
whose properties are inherited is known as Parent class.
• In Method Overloading, Methods of the same class shares the same name but
each method must have a different number of parameters or parameters having
different types and order.
@KUSHALPARIKH11 25
Kushal Parikh
QA Automation Engineer
class Adder {
1
Static int add(int a, int b)
2
{
3
return a+b;
4
}
5
Static double add( double a, double b)
6
{
7
8return a+b;
9}
10public static void main(String args[])
11{
12System.out.println(Adder.add(11,11));
13System.out.println(Adder.add(12.3,12.6));
14}}
Method Overriding:
• In Method Overriding, the subclass has the same method with the same name and
exactly the same number and type of parameters and same return type as a
superclass.
• Method Overriding is to “Change” existing behavior of the method.
• It is a run time polymorphism.
• The methods must have the same signature.
• It always requires inheritance in Method Overriding.
1class Car {
2void run(){
3System.out.println("Car is running");
4}
@KUSHALPARIKH11 26
Kushal Parikh
QA Automation Engineer
class Base {
1
private static void display() {
2
System.out.println("Static or class method from Base");
3
}
4
public void print() {
5
System.out.println("Non-static or instance method from Base");
6
7}
8class Derived extends Base {
9private static void display() {
10System.out.println("Static or class method from Derived");
11}
12public void print() {
13System.out.println("Non-static or instance method from Derived");
@KUSHALPARIKH11 27
Kushal Parikh
QA Automation Engineer
14}
15public class test {
16public static void main(String args[])
17{
18Base obj= new Derived();
19obj1.display();
20
obj1.print();
21
}
22
}
The problem with multiple inheritance is that if multiple parent classes have the
same method name, then at runtime it becomes difficult for the compiler to
decide which method to execute from the child class.
@KUSHALPARIKH11 28
Kushal Parikh
QA Automation Engineer
@KUSHALPARIKH11 29
Kushal Parikh
QA Automation Engineer
It’s important to note that with the introduction of annotations in Java, the use of
marker interfaces has become less common. Annotations offer a more flexible
and expressive way to attach metadata to classes and methods. However,
marker interfaces still have their place in certain contexts and are part of the
Java language’s design and heritage.
@KUSHALPARIKH11 30
Kushal Parikh
QA Automation Engineer
class Demo
1
{
2
int i;
3
public Demo(int a)
4
{
5
6
i=k;
7}
8public Demo(int a, int b)
9{
10//body
11}
12}
@KUSHALPARIKH11 31
Kushal Parikh
QA Automation Engineer
Interfaces:
• Connection
• Statement
• PreparedStatement
• ResultSet
• ResultSetMetaData
• DatabaseMetaData
• CallableStatement etc.
Classes:
• DriverManager
• Blob
• Clob
• Types
• SQLException etc.
@KUSHALPARIKH11 32
Kushal Parikh
QA Automation Engineer
@KUSHALPARIKH11 33
Kushal Parikh
QA Automation Engineer
FALSE when there is no ResultSet object such as running Insert or Update queries.
We can use getResultSet() to get the ResultSet and getUpdateCount() method to
retrieve the update count.
You should use execute() method only when you are not sure about the type of
statement else use executeQuery or executeUpdate method.
1. Statement: Used for general purpose access to the database and executes a static
SQL query at runtime.
2. PreparedStatement: Used to provide input parameters to the query during
execution.
3. CallableStatement: Used to access the database stored procedures and helps in
accepting runtime parameters.
@KUSHALPARIKH11 34