Java Interview Questions For Freshers
Java Interview Questions For Freshers
8. What are the default values assigned to variables and instances in java?
There are no default values assigned to the variables in java. We need to initialize
the value before using it. Otherwise, it will throw a compilation error of (Variable
might not be initialized).
But for instance, if we create the object, then the default value will be initialized
by the default constructor depending on the data type.
If it is a reference, then it will be assigned to null.
If it is numeric, then it will assign to 0.
If it is a boolean, then it will be assigned to false. Etc.
9. What do you mean by data encapsulation?
Data Encapsulation is an Object-Oriented Programming concept of hiding the
data attributes and their behaviours in a single unit.
It helps developers to follow modularity while developing software by ensuring
that each object is independent of other objects by having its own methods,
attributes, and functionalities.
It is used for the security of the private properties of an object and hence serves
the purpose of data hiding.
10. Tell us something about JIT compiler.
JIT stands for Just-In-Time and it is used for improving the performance during
run time. It does the task of compiling parts of byte code having similar
functionality at the same time thereby reducing the amount of compilation time
for the code to run.
The compiler is nothing but a translator of source code to machine-executable
code. But what is special about the JIT compiler? Let us see how it works:
o First, the Java source code (.java) conversion to byte code (.class) occurs
with the help of the javac compiler.
o Then, the .class files are loaded at run time by JVM and with the help of an
interpreter, these are converted to machine understandable code.
o JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM
analyzes the method calls in the .class files and compiles them to get more
efficient and native code. It also ensures that the prioritized method calls
are optimized.
o Once the above step is done, the JVM executes the optimized code
directly instead of interpreting the code again. This increases the
performance and speed of the execution.
11. Can you tell the difference between equals() method and equality
operator (==) in Java?
We are already aware of the (==) equals operator. That we have used this to compare
the equality of the values. But when we talk about the terms of object-oriented
programming, we deal with the values in the form of objects. And this object may
contain multiple types of data. So using the (==) operator does not work in this case.
So we need to go with the .equals() method.
Both [(==) and .equals()] primary functionalities are to compare the values, but the
secondary functionality is different.
So in order to understand this better, let’s consider this with the example -
String str1 = "InterviewBit";
String str2 = "InterviewBit";
System.out.println(str1 == str2);
This code will print true. We know that both strings are equals so it will print true. But
here (==) Operators don’t compare each character in this case. It compares the
memory location. And because the string uses the constant pool for storing the values
in the memory, both str1 and str2 are stored at the same memory location. See the
detailed Explanation in Question no 73: Link.
Now, if we modify the program a little bit with -
String str1 = new String("InterviewBit");
String str2 = "InterviewBit";
System.out.println(str1 == str2);
Then in this case, it will print false. Because here no longer the constant pool concepts
are used. Here, new memory is allocated. So here the memory address is different,
therefore ( == ) Operator returns false. But the twist is that the values are the same in
both strings. So how to compare the values? Here the .equals() method is used.
.equals() method compares the values and returns the result accordingly. If we modify
the above code with -
System.out.println(str1.equals(str2));
Then it returns true.
equals() ==
This is a method defined in the Object class. It is a binary operator in Java.
The .equals() Method is present in the Object
class, so we can override our It cannot be modified. They always
custom .equals() method in the custom class, compare the HashCode.
for objects comparison.
This operator is used for comparing
This method is used for checking the equality
addresses (or references), i.e checks if
of contents between two objects as per the
both the objects are pointing to the same
specified business logic.
memory location.
Note:
In the cases where the equals method is not overridden in a class, then the class
uses the default implementation of the equals method that is closest to the
parent class.
Object class is considered as the parent class of all the java classes. The
implementation of the equals method in the Object class uses the == operator to
compare two objects. This default implementation can be overridden as per the
business logic.
12. How is an infinite loop declared in Java?
Infinite loops are those loops that run infinitely without any breaking conditions. Some
examples of consciously declaring infinite loop is:
Using For Loop:
for (;;)
{
// Business logic
// Any break logic
}
Using while loop:
while(true){
// Business logic
// Any break logic
}
Using do-while loop:
do{
// Business logic
// Any break logic
}while(true);
20. Is it possible that the ‘finally’ block will not be executed? If yes then
list the case.
Yes. It is possible that the ‘finally’ block will not be executed. The cases are-
Suppose we use System.exit() in the above statement.
If there are fatal errors like Stack overflow, Memory access error, etc.
21. Identify the output of the java program and state the reason.
1. public class InterviewBit
2. {
3. public static void main(String[] args) {
4. final int i;
5. i = 20;
6. int j = i+20;
7. i = j+30;
8. System.out.println(i + " " + j);
9. }
10. }
The above code will generate a compile-time error at Line 7 saying - [error: variable i
might already have been initialized]. It is because variable ‘i’ is the final variable. And
final variables are allowed to be initialized only once, and that was already done on line
no 5.
22. When can you use super keyword?
The super keyword is used to access hidden fields and overridden methods or
attributes of the parent class.
Following are the cases when this keyword can be used:
o Accessing data members of parent class when the member names of the
class and its child subclasses are same.
o To call the default and parameterized constructor of the parent class inside
the child class.
o Accessing the parent class methods when the child classes have
overridden them.
The following example demonstrates all 3 cases when a super keyword is used.
class Parent{
protected int num = 1;
Parent(){
System.out.println("Parent class default constructor.");
}
Parent(String x){
System.out.println("Parent class parameterised constructor.");
}
Child(){
//super constructor call should always be in the first line
// super(); // Either call default super() to call
default parent constructor OR
super("Call Parent"); // call parameterised super to call
parameterised parent constructor.
System.out.println("Child class default Constructor");
}
void printNum(){
System.out.println(num);
System.out.println(super.num); //prints the value of num of parent
class
}
@Override
public void foo(){
System.out.println("Child class foo!");
super.foo(); //Calls foo method of Parent class inside the
Overriden foo method of Child class.
}
}
}
}
Output -
Before Changing the value of object 1, the object2 will be -
Object2 Length = 5, Object2 Breadth = 3
}
}
The above snippet will not affect the object2 values. It has its separate values. The
output will be
Before Changing the value of object 1, the object2 will be -
Object2 Length = 5, Object2 Breadth = 3
36. Is this program giving a compile-time error? If Yes then state the
reason and number of errors it will give. If not then state the reason.
abstract final class InterviewBit{
2. public abstract void printMessage();
3. }
4. class ScalarAcademy extends InterviewBit{
5. public void printMessage(){
6. System.out.println("Welcome to Scalar Academy By InterviewBit");
7. }
8. }
9. class ScalarTopics extends ScalarAcademy{
10. public void printMessage(){
11. System.out.println("Welcome to Scalar Topics By Scalar Academy");
12. }
13. }
public class Main{
public static void main(String[] args) {
InterviewBit ib = new ScalarTopics();
ib.printMessage();
}
}
The above program will give a compile-time error. The compiler will throw 2 errors in
this.
[Illegal Combination of modifiers: abstract and final] at line 1.
[Cannot inherit from final ‘InterviewBit’] at line 4.
It is because abstract classes are incomplete classes that need to be inherited for
making their concrete classes. And on the other hand, the final keywords in class are
used for avoiding inheritance. So these combinations are not allowed in java.
37. What is a Comparator in java?
Consider the example where we have an ArrayList of employees like( EId, Ename,
Salary), etc. Now if we want to sort this list of employees based on the names of
employees. Then that is not possible to sort using the Collections.sort() method. We
need to provide something to the sort() function depending on what values we have
to perform sorting. Then in that case a comparator is used.
Comparator is the interface in java that contains the compare method. And by
overloading the compare method, we can define that on what basis we need to
compare the values.
38. In Java, static as well as private method overriding is possible.
Comment on the statement.
The statement in the context is completely False. The static methods have no relevance
with the objects, and these methods are of the class level. In the case of a child class, a
static method with a method signature exactly like that of the parent class can exist
without even throwing any compilation error.
The phenomenon mentioned here is popularly known as method hiding, and
overriding is certainly not possible. Private method overriding is unimaginable because
the visibility of the private method is restricted to the parent class only. As a result,
only hiding can be facilitated and not overriding.
39. What makes a HashSet different from a TreeSet?
Although both HashSet and TreeSet are not synchronized and ensure that duplicates
are not present, there are certain properties that distinguish a HashSet from a TreeSet.
Implementation: For a HashSet, the hash table is utilized for storing the
elements in an unordered manner. However, TreeSet makes use of the red-black
tree to store the elements in a sorted manner.
Complexity/ Performance: For adding, retrieving, and deleting elements, the
time amortized complexity is O(1) for a HashSet. The time complexity for
performing the same operations is a bit higher for TreeSet and is equal to O(log
n). Overall, the performance of HashSet is faster in comparison to TreeSet.
Methods: hashCode() and equals() are the methods utilized by HashSet for
making comparisons between the objects. Conversely, compareTo() and
compare() methods are utilized by TreeSet to facilitate object comparisons.
Objects type: Heterogeneous and null objects can be stored with the help of
HashSet. In the case of a TreeSet, runtime exception occurs while inserting
heterogeneous objects or null objects.
40. Why is the character array preferred over string for storing
confidential information?
In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it
continues to stay in the string pool as long as it is not removed in the form of garbage.
In other words, a string resides in the heap section of the memory for an unregulated
and unspecified time interval after string value processing is executed.
As a result, vital information can be stolen for pursuing harmful activities by hackers if
a memory dump is illegally accessed by them. Such risks can be eliminated by using
mutable objects or structures like character arrays for storing any variable. After the
work of the character array variable is done, the variable can be configured to blank at
the same instant. Consequently, it helps in saving heap memory and also gives no
chance to the hackers to extract vital data.
41. What do we get in the JDK file?
JDK- For making java programs, we need some tools that are provided by JDK
(Java Development Kit). JDK is the package that contains various tools,
Compiler, Java Runtime Environment, etc.
JRE - To execute the java program we need an environment. (Java Runtime
Environment) JRE contains a library of Java classes + JVM. What are JAVA
Classes? It contains some predefined methods that help Java programs to use
that feature, build and execute. For example - there is a system class in java
that contains the print-stream method, and with the help of this, we can print
something on the console.
JVM - (Java Virtual Machine) JVM is a part of JRE that executes the Java
program at the end. Actually, it is part of JRE, but it is software that converts
bytecode into machine-executable code to execute on hardware.
42. What are the differences between JVM, JRE and JDK in Java?
Criteria JDK JRE JVM
Abbreviation Java Development Java Runtime
Java Virtual Machine
Kit Environment
Definition JDK is a complete JRE is a software JVM is a platform-dependent,
Criteria JDK JRE JVM
abstract machine comprising of
3 specifications - document
software package providing
describing the JVM
development kit for Java class libraries,
implementation requirements,
developing Java JVM and all the
computer program meeting the
applications. It required
JVM requirements and instance
comprises JRE, components to run
object for executing the Java
JavaDoc, compiler, the Java
byte code and provide the
debuggers, etc. applications.
runtime environment for
execution.
Main JDK is mainly used JRE is mainly used
Purpose for code for environment JVM provides specifications for
development and creation to execute all the implementations to JRE.
execution. the code.
Tools JRE provides
JDK provides tools
provided libraries and JVM does not include any tools,
like compiler,
classes required by but instead, it provides the
debuggers, etc for
JVM to run the specification for implementation.
code development
program.
Summary JRE = (JVM) +
JDK = (JRE) + Libraries to JVM = Runtime environment to
Development tools execute the execute Java byte code.
application
43. What are the differences between HashMap and HashTable in Java?
HashMap HashTable
HashMap is not synchronized thereby making HashTable is synchronized and hence it
it better for non-threaded applications. is suitable for threaded applications.
Allows only one null key but any number of This does not allow null in both keys or
null in the values. values.
Supports order of insertion by making use of Order of insertion is not guaranteed in
its subclass LinkedHashMap. HashTable.
44. What is the importance of reflection in Java?
The term reflection is used for describing the inspection capability of a code
on other code either of itself or of its system and modify it during runtime.
Consider an example where we have an object of unknown type and we have a
method ‘fooBar()’ which we need to call on the object. The static typing system
of Java doesn't allow this method invocation unless the type of the object is
known beforehand. This can be achieved using reflection which allows the code
to scan the object and identify if it has any method called “fooBar()” and only
then call the method if needed.
Method methodOfFoo = fooObject.getClass().getMethod("fooBar", null);
methodOfFoo.invoke(fooObject, null);
Using reflection has its own cons:
o Speed — Method invocations due to reflection are about three times
slower than the direct method calls.
o Type safety — When a method is invoked via its reference wrongly using
reflection, invocation fails at runtime as it is not detected at compile/load
time.
o Traceability — Whenever a reflective method fails, it is very difficult to
find the root cause of this failure due to a huge stack trace. One has to
deep dive into the invoke() and proxy() method logs to identify the root
cause.
Hence, it is advisable to follow solutions that don't involve reflection and use
this method as a last resort.
45. What are the different ways of threads usage?
We can define and implement a thread in java using two ways:
o Extending the Thread class
class InterviewBitThreadExample extends Thread{
public void run(){
System.out.println("Thread runs...");
}
public static void main(String args[]){
InterviewBitThreadExample ib = new InterviewBitThreadExample();
ib.start();
}
}
Implementing the Runnable interface
class InterviewBitThreadExample implements Runnable{
public void run(){
System.out.println("Thread runs...");
}
public static void main(String args[]){
Thread ib = new Thread(new InterviewBitThreadExample());
ib.start();
}
}
Implementing a thread using the method of Runnable interface is more
preferred and advantageous as Java does not have support for multiple
inheritances of classes.
start() method is used for creating a separate call stack for the thread
execution. Once the call stack is created, JVM calls the run() method for
executing the thread in that call stack.
46. What are the different types of Thread Priorities in Java? And what is
the default priority of a thread assigned by JVM?
There are a total of 3 different types of priority available in Java.
MIN_PRIORITY: It has an integer value assigned with 1.
MAX_PRIORITY: It has an integer value assigned with 10.
NORM_PRIORITY: It has an integer value assigned with 5.
In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default
priority for any thread is NORM_PRIORITY assigned by JVM.
47. What is the difference between the program and the process?
A program can be defined as a line of code written in order to accomplish a
particular task. Whereas the process can be defined as the programs which are
under execution.
A program doesn't execute directly by the CPU. First, the resources are allocated
to the program and when it is ready for execution then it is a process.
48. What is the difference between the ‘throw’ and ‘throws’ keyword in
java?
The ‘throw’ keyword is used to manually throw the exception to the calling
method.
And the ‘throws’ keyword is used in the function definition to inform the calling
method that this method throws the exception. So if you are calling, then you
have to handle the exception.
Example -
class Main {
public static int testExceptionDivide(int a, int b) throws
ArithmeticException{
if(a == 0 || b == 0)
throw new ArithmeticException();
return a/b;
}
public static void main(String args[]) {
try{
testExceptionDivide(10, 0);
}
catch(ArithmeticException e){
//Handle the exception
}
}
}
Here in the above snippet, the method testExceptionDivide throws an exception. So if
the main method is calling it then it must have handled the exception. Otherwise, the
main method can also throw the exception to JVM.
And the method testExceptionDivide 'throws’ the exception based on the condition.
49. What are the differences between constructor and method of a class
in Java?
Constructor Method
Method is used for exposing the
Constructor is used for initializing the object state.
object's behavior.
Method should have a return
Constructor has no return type. type. Even if it does not return
anything, return type is void.
Method has to be invoked on
Constructor gets invoked implicitly.
the object explicitly.
If the constructor is not defined, then a default If a method is not defined, then
constructor is provided by the java compiler. the compiler does not provide it.
The name of the method can
The constructor name should be equal to the class
have any name or have a class
name.
name too.
A constructor cannot be marked as final because
whenever a class is inherited, the constructors are not A method can be defined as
inherited. Hence, marking it final doesn't make sense. final but it cannot be overridden
Java throws compilation error saying - modifier final in its subclasses.
not allowed here
A final variable if initialised
Final variable instantiations are possible inside a inside a method ensures that
constructor and the scope of this applies to the whole the variable cant be changed
class and its objects. only within the scope of that
method.
Identify the output of the below java program and Justify your answer.
class Main {
public static void main(String args[]) {
Scaler s = new Scaler(5);
}
}
class InterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
class Scaler extends InterviewBit{
Scaler(){
System.out.println(" Welcome to Scaler Academy ");
}
Scaler(int x){
this();
super();
System.out.println(" Welcome to Scaler Academy 2");
}
}
The above code will throw the compilation error. It is because the super() is used to
call the parent class constructor. But there is the condition that super() must be the
first statement in the block. Now in this case, if we replace this() with super() then
also it will throw the compilation error. Because this() also has to be the first statement
in the block. So in conclusion, we can say that we cannot
use this() and super() keywords in the same block.
51. Java works as “pass by value” or “pass by reference” phenomenon?
Java always works as a “pass by value”. There is nothing called a “pass by reference” in
Java. However, when the object is passed in any method, the address of the value is
passed due to the nature of object handling in Java. When an object is passed, a copy
of the reference is created by Java and that is passed to the method. The objects point
to the same memory location. 2 cases might happen inside the method:
Case 1: When the object is pointed to another location: In this case, the changes made
to that object do not get reflected the original object before it was passed to the
method as the reference points to another location.
For example:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver {
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in
the object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// Point the object to new reference
ibObj = new InterviewBitTest();
// Update the value
ibObj.num = 50;
}
}
Output:
20
Case 2: When object references are not modified: In this case, since we have the copy
of reference the main object pointing to the same memory location, any changes in the
content of the object get reflected in the original object.
For example:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver{
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in
the object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// no changes are made to point the ibObj to new location
// Update the value of num
ibObj.num = 50;
}
}
Output:
50
Exception Handling
Easy
5.9 Mins
Solve
Easy
3.36 Mins
Solve
Finally Block
Easy
2.45 Mins
Solve
Now if we want to access index 4. Then internally java calculates the address using the
formula-
[Base Address + (index * no_of_bytes)]. So according to this. The starting address of
the index 4 will be - [100 + (4*4)] = 116. And exactly that's what the address is
calculated.
Now consider the same with 1 index Array -
Now if we apply the same formula here. Then we get - 116 as the starting address of
the 4th index. Which is wrong. Then we need to apply formula - [Base Address +
((index-1) * no_of_bytes)].
And for calculating this, an extra arithmetic operation has to be performed. And
consider the case where millions of addresses need to be calculated, this causes
complexity. So to avoid this, ) the index array is supported by java.
67. Why is the remove method faster in the linked list than in an array?
In the linked list, we only need to adjust the references when we want to delete the
element from either end or the front of the linked list. But in the array, indexes are
used. So to manage proper indexing, we need to adjust the values from the array So
this adjustment of value is costlier than the adjustment of references.
Example - To Delete from the front of the linked list, internally the references
adjustments happened like this.
The only thing that will change is that the head pointer will point to the head’s next
node. And delete the previous node. That is the constant time operation.
Whereas in the ArrayList, internally it should work like this-
For deletion of the first element, all the next element has to move to one place ahead.
So this copying value takes time. So that is the reason why removing in ArrayList is
slower than LinkedList.
68. How many overloaded add() and addAll() methods are available in
the List interface? Describe the need and uses.
There are a total of 4 overloaded methods for add() and addAll() methods available in
List Interface. The below table states the description of all.
Return Type Method Description
boolean add(Element e): This method is used for adding the element at the end of the
List. The Datatype of the element is of any type it has been initially assigned with.
It returns the boolean indicating successfully inserted or not.
void add(int index, Element e): This method is the overloaded version of add()
method. In this, along with the element, the index is also passed to the method
for the specific index the value needs to be inserted.
boolean addAll(Collection <extends ? Element > c): This method helps to add all
elements at the end of collections from the list received in the parameter. It
contains an iterator that helps to iterate the list and add the elements to the
collection.
boolean addAll(int index, Collection <extends ? Element > c): This is the overloaded
method for addAll() method. In this along with the list, we can pass the specified
index from which the list elements need to be added.
69. How does the size of ArrayList grow dynamically? And also state
how it is implemented internally.
ArrayList is implemented in such a way that it can grow dynamically. We don't need to
specify the size of ArrayList. For adding the values in it, the methodology it uses is -
1. Consider initially that there are 2 elements in the ArrayList. [2, 3].
2. If we need to add the element into this. Then internally what will happen is-
ArrayList will allocate the new ArrayList of Size (current size + half of the current size).
And add the old elements into the new. Old - [2, 3], New - [2, 3, null].
Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the
extra space will be available for the value to be inserted.
3. This process continues and the time taken to perform all of these is considered as
the amortized constant time.
This is how the ArrayList grows dynamically. And when we delete any entry from the
ArrayList then the following steps are performed -
1. It searches for the element index in the array. Searching takes some time. Typically
it’s O(n) because it needs to search for the element in the entire array.
2. After searching the element, it needs to shift the element from the right side to fill
the index.
So this is how the elements are deleted from the ArrayList internally. Similarly, the
search operations are also implemented internally as defined in removing elements
from the list (searching for elements to delete).
71. What is the difference between ‘>>’ and ‘>>>’ operators in java?
These 2 are the bitwise right shift operators. Although both operators look similar. But
there is a minimal difference between these two right shift operators.
‘>>’ Bitwise Right Shift Operator- This operator shifts each bit to its right position.
And this maintains the signed bit.
‘>>>’ Bitwise Right Shift Operator with trailing zero- This operator also shifts each
bit to its right. But this doesn’t maintain the signed bit. This operator makes the Most
significant bit to 0.
Example- Num1 = 8, Num2 = -8.
So the binary form of these numbers are -
Num1 = 00000000 00000000 00000000 00001000
Num2 = 11111111 11111111 11111111 11111000
‘>>’ Operator : 8 >> 1 (Shift by one bit) :
Num1 = 00000000 00000000 00000000 00000100
Num2 = 11111111 11111111 11111111 11111100
‘>>>’ Operator : 8 >>> 1 (Shift by one bit) =
Num1 = 00000000 00000000 00000000 00000100
Num2 = 01111111 11111111 11111111 11111100
72. What are Composition and Aggregation? State the difference.
Composition, and Aggregation help to build (Has - A - Relationship) between classes
and objects. But both are not the same in the end. Let’s understand with the help of
an example.
Consider the University as a class that has some departments in it. So the university will
be the container object. And departments in it will contain objects. Now in this case, if
the container object destroys then the contained objects will also get destroyed
automatically. So here we can say that there is a strong association between the
objects. So this Strong Association is called Composition.
Now consider one more example. Suppose we have a class department and there are
several professors' objects there in the department. Now if the department class is
destroyed then the professor's object will become free to bind with other objects.
Because container objects (Department) only hold the references of contained objects
(Professor’s). So here is the weak association between the objects. And this weak
association is called Aggregation.
73. How is the creation of a String using new() different from that of a
literal?
When a String is formed as a literal with the assistance of an assignment operator, it
makes its way into the String constant pool so that String Interning can take place.
This same object in the heap will be referenced by a different String if the content is
the same for both of them.
public bool checking() {
String first = "InterviewBit";
String second = "InterviewBit";
if (first == second)
return true;
else
return false;
}
The checking() function will return true as the same content is referenced by both the
variables.
Conversely, when a String formation takes place with the help of a new() operator,
interning does not take place. The object gets created in the heap memory even if the
same content object is present.
public bool checking() {
String first = new String("InterviewBit");
String second = new String("InterviewBit");
if (first == second)
return true;
else
return false;
}
The checking() function will return false as the same content is not referenced by both
the variables.
74. How is the ‘new’ operator different from the ‘newInstance()’
operator in java?
Both ‘new’ and ‘newInstance()’ operators are used to creating objects. The difference
is- that when we already know the class name for which we have to create the object
then we use a new operator. But suppose we don’t know the class name for which we
need to create the object, Or we get the class name from the command line argument,
or the database, or the file. Then in that case we use the ‘newInstance()’ operator.
The ‘newInstance()’ keyword throws an exception that we need to handle. It is
because there are chances that the class definition doesn’t exist, and we get the class
name from runtime. So it will throw an exception.
75. Is exceeding the memory limit possible in a program despite having
a garbage collector?
Yes, it is possible for the program to go out of memory in spite of the presence of a
garbage collector. Garbage collection assists in recognizing and eliminating those
objects which are not required in the program anymore, in order to free up the
resources used by them.
In a program, if an object is unreachable, then the execution of garbage collection
takes place with respect to that object. If the amount of memory required for creating
a new object is not sufficient, then memory is released for those objects which are no
longer in the scope with the help of a garbage collector. The memory limit is exceeded
for the program when the memory released is not enough for creating new objects.
Moreover, exhaustion of the heap memory takes place if objects are created in such a
manner that they remain in the scope and consume memory. The developer should
make sure to dereference the object after its work is accomplished. Although the
garbage collector endeavors its level best to reclaim memory as much as possible,
memory limits can still be exceeded.
Let’s take a look at the following example:
List<String> example = new LinkedList<String>();
while(true){
example.add(new String("Memory Limit Exceeded"));
}
76. Why is synchronization necessary? Explain with the help of a relevant example.
Concurrent execution of different processes is made possible by synchronization.
When a particular resource is shared between many threads, situations may arise in
which multiple threads require the same shared resource.
Synchronization assists in resolving the issue and the resource is shared by a single
thread at a time. Let’s take an example to understand it more clearly. For example, you
have a URL and you have to find out the number of requests made to it. Two
simultaneous requests can make the count erratic.
No synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11.
Simultaneously, if another thread Thread2 views the count as 10, it will be increased by
1 to 11. Thus, inconsistency in count values takes place because the expected final
value is 12 but the actual final value we get will be 11.
Now, the function increase() is made synchronized so that simultaneous accessing
cannot take place.
With synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public synchronized int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the
thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus,
consistency in count values takes place.
77. In the given code below, what is the significance of ... ?
public void fooBarMethod(String... variables){
// method code
}
Ability to provide ... is a feature called varargs (variable arguments) which was
introduced as part of Java 5.
The function having ... in the above example indicates that it can receive multiple
arguments of the datatype String.
For example, the fooBarMethod can be called in multiple ways and we can still have
one method to process the data as shown below:
fooBarMethod("foo", "bar");
fooBarMethod("foo", "bar", "boo");
fooBarMethod(new String[]{"foo", "var", "boo"});
public void myMethod(String... variables){
for(String variable : variables){
// business logic
}
}
78. What will be the output of the below java program and define the
steps of Execution of the java program with the help of the below code?
class InterviewBit{
int i;
static int j;
{
System.out.println(" Instance Block 1. Value of i = "+i);
}
static{
System.out.println(" Static Block 1. Value of j = "+j);
method_2();
}
{
i = 5;
}
static{
j = 10;
}
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
public static void main(String[] args){
InterviewBit ib = new InterviewBit();
}
public void method_1(){
System.out.println(" Instance method. ");
}
static{
System.out.println(" Static Block 2. Value of j = "+j);
}
{
System.out.println(" Instance Block 2. Value of i = "+i);
method_1();
}
public static void method_2(){
System.out.println(" Static method. ");
}
}
The Output we get by executing this program will be
Static Block 1. Value of j = 0
Static method.
Static Block 2. Value of j = 10
Instance Block 1. Value of i = 0
Instance Block 2. Value of i = 5
Instance method.
Welcome to InterviewBit
This is a java tricky interview question frequently asked in java interviews for the
experienced. The output will be like this because, when the java program is compiled
and gets executed, then there are various steps followed for execution. And the steps
are -
Identification of Static Members from top to bottom.
Execution of Static variable assignment and a Static block from top to bottom.
Execution of the main method.
Identification of Instance Members from top to bottom.
Execution of Instance variable assignment and Instance block from top to bottom.
Execution of Constructor.
In above steps from 4 to 6, will be executed for every object creation. If we create
multiple objects then for every object these steps will be performed.
Now from the above code, the execution will happen like this -
1. In the step of identification of static members. It is found that -
static int j.
static block.
main method.
static method_2.
During identification, the JVM will assign the default value in the static int j variable.
Then it is currently in the state of reading and indirectly writing. Because the original
value is not assigned.
2. In the next step, it will execute the static block and assign the value in static
variables.
First static block it will print and because execution from top to bottom and original
value in j is not assigned. So it will print the default value of 0.
After executing static block 1. It will execute the static method_1 because it is called
from the static block 1.
Then it will assign the original value of 5 in the j variable. And executes the remaining
static block.
3. Now it will execute the main method. In which it will create an object for the class
InterviewBit. And then the execution of instances will happen.
4. Identify the instance variables and blocks from top to bottom.
int i.
Instance block 1.
Instance method_1.
Like a static variable, the instance variable also has been initialized with the default
value 0 and will be in the state of reading and writing indirectly.
5. It will execute the instance methods and assign the original value to the instance
variable.
Prints the Instance block 1. And the current value of i is not assigned till now, so it will
print 0.
Assign the original value to i. Then print instance block 2. And after that instance
method will be called and printed because it is being called in the instance block.
6. And at the last step, the constructor will be invoked and the lines will be executed in
the constructor.
This is how the java program gets executed.
79. Define System.out.println().
System.out.println() is used to print the message on the console. System - It is a
class present in java.lang package. Out is the static variable of type PrintStream class
present in the System class. println() is the method present in the PrintStream class.
So if we justify the statement, then we can say that if we want to print anything on the
console then we need to call the println() method that was present in PrintStream
class. And we can call this using the output object that is present in the System class.
80. Can you explain the Java thread lifecycle?
Java thread life cycle is as follows:
New – When the instance of the thread is created and the start() method has not been
invoked, the thread is considered to be alive and hence in the NEW state.
Runnable – Once the start() method is invoked, before the run() method is called by
JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be
entered from the Waiting or Sleeping state of the thread.
Running – When the run() method has been invoked and the thread starts its
execution, the thread is said to be in a RUNNING state.
Non-Runnable (Blocked/Waiting) – When the thread is not able to run despite the
fact of its aliveness, the thread is said to be in a NON-RUNNABLE state. Ideally, after
some time of its aliveness, the thread should go to a runnable state.
o A thread is said to be in a Blocked state if it wants to enter synchronized code
but it is unable to as another thread is operating in that synchronized block on
the same object. The first thread has to wait until the other thread exits the
synchronized block.
o A thread is said to be in a Waiting state if it is waiting for the signal to execute
from another thread, i.e it waits for work until the signal is received.
Terminated – Once the run() method execution is completed, the thread is said to
enter the TERMINATED step and is considered to not be alive.
The following flowchart clearly explains the lifecycle of the thread in Java.
81. What could be the tradeoff between the usage of an unordered
array versus the usage of an ordered array?
The main advantage of having an ordered array is the reduced search time complexity
of O(log n) whereas the time complexity in an unordered array is O(n).
The main drawback of the ordered array is its increased insertion time which is O(n)
due to the fact that its element has to reordered to maintain the order of array during
every insertion whereas the time complexity in the unordered array is only O(1).
Considering the above 2 key points and depending on what kind of scenario a
developer requires, the appropriate data structure can be used for implementation.
82. Is it possible to import the same class or package twice in Java and
what happens to it during runtime?
It is possible to import a class or package more than once, however, it is redundant
because the JVM internally loads the package or class only once.
83. In case a package has sub packages, will it suffice to import only the
main package? e.g. Does importing of com.myMainPackage.* also
import com.myMainPackage.mySubPackage.*?
This is a big NO. We need to understand that the importing of the sub-packages of a
package needs to be done explicitly. Importing the parent package only results in the
import of the classes within it and not the contents of its child/sub-packages.
84. Will the finally block be executed if the code System.exit(0) is
written at the end of try block?
NO. The control of the program post System.exit(0) is immediately gone and the
program gets terminated which is why the finally block never gets executed.
85. What do you understand by marker interfaces in Java?
Marker interfaces, also known as tagging interfaces are those interfaces that have no
methods and constants defined in them. They are there for helping the compiler and
JVM to get run time-related information regarding the objects.
86. Explain the term “Double Brace Initialisation” in Java?
This is a convenient means of initializing any collections in Java. Consider the below
example.
import java.util.HashSet;
import java.util.Set;
doSomething(stringSets);
}
90. In the below Java Program, how many objects are eligible for
garbage collection?
class Main{
public static void main(String[] args){
int[][] num = new int[3][];
num[0] = new int[5];
num[1] = new int[2];
num[2] = new int[3];
return word.charAt(word.length()- 1) +
getReverseWord(word.substring(0, word.length() - 1));
}
}
Practice Problems
Solve these problems to ace this concept
Substring
Medium
9.54 Mins
Solve
StringBuffer
Easy
24.17 Mins
Solve
int[] array={4,3,8,7,5,2,6};
int missingNumber = findMissingNum(array);
System.out.println("Missing Number is "+ missingNumber);
}
//Pointers.
int i = 0, j = str.length()-1;
System.out.println("\n");
//Rotation
//Transpose
for(int i = 0; i < no; i++){
for(int j = i; j < no; j++){
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
//Calculating Mid.
int mid = (low + high)/2;
//Base Case.
if(low > high)
return false;
Stack is a linear data structure where data Queue is a linear data structure where data is ended
is added and removed from the top. at the rear end and removed from the front.
Delete operation in Stack is known as pop. Delete operation in Queue is known as dequeue.
Only one pointer is available for both Two pointers are available for addition and deletion:
addition and deletion: top() front() and rear()
Practice Problems
Solve these problems to ace this concept
Evaluate Expression
Easy
32.46 Mins
Solve
Level Order
Easy
29.55 Mins
Solve
14. What is array data structure? What are the applications of arrays?
An array data structure is a data structure that is used to store data in a way that is
efficient and easy to access. It is similar to a list in that it stores data in a sequence.
However, an array data structure differs from a list in that it can hold much more data
than a list can. An array data structure is created by combining several arrays together.
Each array is then given a unique identifier, and each array’s data is stored in the order
in which they are created.
Array data structures are commonly used in databases and other computer systems to
store large amounts of data efficiently. They are also useful for storing information
that is frequently accessed, such as large amounts of text or images.
Practice Problems
Solve these problems to ace this concept
Easy
33.39 Mins
+4
Solve
3. Circular Linked List: A circular linked list is a unidirectional linked list where each
node points to its next node and the last node points back to the first node, which
makes it circular.
4. Doubly Circular Linked List: A doubly circular linked list is a linked list where each
node points to its next node and its previous node and the last node points back to
the first node and first node’s previous points to the last node.
5. Header List: A list that contains the header node at the beginning of the list, is
called the header-linked list. This is helpful in calculating some repetitive operations
like the number of elements in the list etc.
18. Difference between Array and Linked List.
Arrays Linked Lists
It keeps the data elements in a single It stores elements at random, or anywhere in the
memory. memory.
The memory size of an array is fixed The memory size of a linked list is allocated during
and cannot be changed during runtime. runtime.
Operations like insertion and deletion Operations like insertion and deletion are faster in the
take longer time in an array. linked list.
Practice Problems
Solve these problems to ace this concept
Rotate List
Medium
33.58 Mins
Solve
Practice Problems
Solve these problems to ace this concept
Inorder Traversal
Easy
32.0 Mins
Solve
27. What is a deque data structure and its types? What are the
applications for deque?
A deque can be thought of as an array of items, but with one important difference:
Instead of pushing and popping items off the end to make room, deques are designed
to allow items to be inserted at either end. This property makes deques well-suited for
performing tasks such as keeping track of inventory, scheduling tasks, or handling
large amounts of data.
There are two types of deque:
Input Restricted Deque: Insertion operations are performed at only one end while
deletion is performed at both ends in the input restricted queue.
Output Restricted Deque: Deletion operations are performed at only one end while
insertion is performed at both ends in the output restricted queue.
Following are some real-time applications for deque data structure:
It can be used as both stack and queue, as it supports all the operations for both data
structures.
Web browser’s history can be stored in a deque.
Operating systems job scheduling algorithm.
28. What are some key operations performed on the Deque data
structure?
Following are the key operations available deque:
insertFront(): This adds an element to the front of the Deque.
insertLast(): This adds an element to the rear of the Deque.
deleteFront(): This deletes an element from the front of the Deque.
deleteLast():This deletes an element from the front of the Deque.
getFront(): This gets an element from the front of the Deque.
getRear(): This gets an element from the rear of the Deque.
isEmpty(): This checks whether Deque is empty or not.
isFull(): This checks whether Deque is full or not.
29. What is a priority queue? What are the applications for priority
queue?
Priority Queue is an abstract data type that is similar to a queue in that each element is
assigned a priority value. The order in which elements in a priority queue are served is
determined by their priority (i.e., the order in which they are removed). If the elements
have the same priority, they are served in the order they appear in the queue.
Following are some real-time applications for priority queue:
Used in graph algorithms like Dijkstra, Prim’s Minimum spanning tree etc.
Huffman code for data compression
Finding Kth Largest/Smallest element
30. Compare different implementations of priority queue
The following table contains an asymptotic analysis of different implementations of a
priority queue:
Operations peek insert delete
31. What is graph data structure and its representations? What are the
applications for graphs?
A graph is a type of non-linear data structure made up of nodes and edges. The nodes
are also known as vertices, and edges are lines or arcs that connect any two nodes in
the graph.
The following are the two most common graph representations:
1. Adjacency Matrix: Adjacency Matrix is a two-dimensional array with the
dimensions V x V, where V is the number of vertices in a graph. Representation is
simpler to implement and adhere to. It takes O(1) time to remove an edge. Queries
such as whether there is an edge from vertex 'u' to vertex 'v' are efficient and can be
completed in O(1).
One of the cons of this representation is that even if the graph is sparse (has fewer
edges), it takes up the same amount of space. Adding a vertex takes O(V^2). It also
takes O(V) time to compute all of a vertex's neighbours, which is not very efficient.
2. Adjacency List: In this method, each Node holds a list of Nodes that are directly
connected to that vertex. Each node at the end of the list is connected with null values
to indicate that it is the last node in the list. This saves space O(|V|+|E|). In the worst-
case scenario, a graph can have C(V, 2) edges, consuming O(V^2) space. It is simpler
to add a vertex. It takes the least amount of time to compute all of a vertex's
neighbours.
One of the cons of this representation is that queries such as "is there an edge from
vertex u to vertex v?" are inefficient and take O (V) in the worst case.
32. What is the difference between the Breadth First Search (BFS) and
Depth First Search (DFS)?
Breadth First Search (BFS) Depth First Search (DFS)
It stands for “Breadth First Search” It stands for “Depth First Search”
We walk through all nodes on the same DFS begins at the root node and proceeds as far as
level before passing to the next level in possible through the nodes until we reach the node
BFS. with no unvisited nearby nodes.
When compared to DFS, BFS is slower. When compared to BFS, DFS is faster.
BFS performs better when the target is DFS performs better when the target is far from the
close to the source. source.
Nodes that have been traversed multiple When there are no more nodes to visit, the visited
times are removed from the queue. nodes are added to the stack and then removed.
Practice Problems
Solve these problems to ace this concept
Word Ladder I
Hard
69.43 Mins
Solve
Valid Path
Medium
84.37 Mins
Solve
33. What is AVL tree data structure, its operations, and its rotations?
What are the applications for AVL trees?
AVL trees are height balancing binary search trees named after their inventors
Adelson, Velski, and Landis. The AVL tree compares the heights of the left and right
subtrees and ensures that the difference is less than one. This distinction is known as
the Balance Factor.
BalanceFactor = height(left-subtree) − height(right-subtree)
We can perform the following two operations on AVL tree:
Insertion: Insertion in an AVL tree is done in the same way that it is done in a binary
search tree. However, it may cause a violation in the AVL tree property, requiring the
tree to be balanced. Rotations can be used to balance the tree.
Deletion: Deletion can also be performed in the same manner as in a binary search
tree. Because deletion can disrupt the tree's balance, various types of rotations are
used to rebalance it.
An AVL tree can balance itself by performing the four rotations listed below:
Left rotation: When a node is inserted into the right subtree of the right subtree and
the tree becomes unbalanced, we perform a single left rotation.
Right rotation: If a node is inserted in the left subtree of the left subtree, the AVL tree
may become unbalanced. The tree then requires right rotation.
Left-Right rotation: The RR rotation is performed first on the subtree, followed by the
LL rotation on the entire tree.
Right-Left rotation: The LL rotation is performed first on the subtree, followed by the
RR rotation on the entire tree.
Following are some real-time applications for AVL tree data structure:
AVL trees are typically used for in-memory sets and dictionaries.
AVL trees are also widely used in database applications where there are fewer
insertions and deletions but frequent data lookups are required.
Apart from database applications, it is used in applications that require improved
searching.
34. What is a B-tree data structure? What are the applications for B-
trees?
The B Tree is a type of m-way tree that is commonly used for disc access. A B-Tree
with order m can only have m-1 keys and m children. One of the primary reasons for
using a B tree is its ability to store a large number of keys in a single node as well as
large key values while keeping the tree's height relatively small.
A B-tree of order 4 is shown below in the image:
Following are the key properties of a B-tree data structure:
All of the leaves are at the same height.
The term minimum degree 't' describes a B-Tree. The value of t is determined by the
size of the disc block.
Except for root, every node must have at least t-1 keys. The root must contain at least
one key.
All nodes (including root) can have no more than 2*t - 1 keys.
The number of children of a node is equal to its key count plus one.
A node's keys are sorted in ascending order. The child of two keys k1 and k2 contains
all keys between k1 and k2.
In contrast to Binary Search Tree, B-Tree grows and shrinks from the root.
Following are real-time applications of a B-Tree data structure:
It is used to access data stored on discs in large databases.
Using a B tree, you can search for data in a data set in significantly less time.
The indexing feature allows for multilevel indexing.
The B-tree approach is also used by the majority of servers.
35. Define Segment Tree data structure and its applications.
A segment Tree is a binary tree that is used to store intervals or segments. The
Segment Tree is made up of nodes that represent intervals. Segment Tree is used
when there are multiple range queries on an array and changes to array elements.
The segment tree of array A[7] will look like this:
Following are key operations performed on the Segment tree data structure:
Building Tree: In this step, we create the structure and initialize the segment tree
variable.
Updating the Tree: In this step, we change the tree by updating the array value at a
point or over an interval.
Querying Tree: This operation can be used to run a range query on the array.
Following are real-time applications for Segment Tree:
Used to efficiently list all pairs of intersecting rectangles from a list of rectangles in the
plane.
The segment tree has become popular for use in pattern recognition and image
processing.
Finding range sum/product, range max/min, prefix sum/product, etc
Computational geometry
Geographic information systems
Static and Dynamic RMQ (Range Minimum Query)
Storing segments in an arbitrary manner
36. Define Trie data structure and its applications
The word "Trie" is an abbreviation for "retrieval." Trie is a data structure that stores a
set of strings as a sorted tree. Each node has the same number of pointers as the
number of alphabet characters. It can look up a word in the dictionary by using its
prefix. Assuming that all strings are formed from the letters 'a' to 'z' in the English
alphabet, each trie node can have a maximum of 26 points.
Trie is also referred to as the digital tree or the prefix tree. The key to which a node is
connected is determined by its position in the Trie. Trie allows us to insert and find
strings in O(L) time, where L is the length of a single word. This is clearly faster than
BST. Because of how it is implemented, this is also faster than Hashing. There is no
need to compute a hash function. There is no need to handle collisions (like we do in
open addressing and separate chaining)
Another benefit of Trie is that we can easily print all words in alphabetical order, which
is not easy with hashing. Trie can also perform prefix search (or auto-complete)
efficiently.
The main disadvantage of tries is that they require a large amount of memory to store
the strings. We have an excessive number of node pointers for each node
class Solution{
public:
//function that takes an array and its size as arguments
int removeDuplicates(int a[],int n){
int index=0;
for(int i=1;i<n;i++) {
int main()
{
int T;
//taking the number of test cases from user
cin>>T;
//running the loop for all test cases
while(T--)
{
int N;
//taking size input from user
cin>>N;
int a[N];
//taking array input from user
for(int i=0;i<N;i++)
{
cin>>a[i];
}
Solution ob;
//calling the removeDuplicates in the Solution class
int n = ob.removeDuplicates(a,N);
//printing the array after removing duplicates
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
}
Time Complexity: O(n)
Space Complexity: O(1)
41. Write a function for zigzag traversal in a binary tree
Input:
Output: [1, 3, 2, 4, 5, 6, 8, 7]
Explanation: Zigzag Traversal first iterates the given level of the tree from left to right
and then the next level as the right to the level.
// Tree Node
struct Node {
int data;
Node* left;
Node* right;
};
if(temp->left)
st2.push(temp->left);
if(temp->right)
st2.push(temp->right);
}
//Iterate until the second stack is not empty
while(!st2.empty()){
Node* temp=st2.top();
st2.pop();
result.push_back(temp->data);
if(temp->right)
st1.push(temp->right);
if(temp->left)
st1.push(temp->left);
}
}
return result;
}
Time Complexity: O(n)
Space Complexity: O(n)
42. Write a function to sort a linked list of 0s, 1s and 2s
Input: 0->1->0->2->1->0->2->1
Output: 0->0->0->1->1->1->2->2
Explanation: All 0’s will come first then 1s and then 2s. This can be done in O(n) time
by counting the occurrences of all three and rearranging them in the linked list.
//structure of the linked list
struct Node {
int data;
Node *left;
Node *right;
}
//function take the head of the linked list as a parameter
void sortList(Node *head)
{
//if linked list is empty then return back
if(head==NULL)
return;
else
{
Node *temp=head;
Node *temp1=head;
//to store count of 0s, 1s, and 2s
int count0=0,count1=0,count2=0;
//calculating the count of 0s, 1s, and 2s
while(temp!=NULL)
{
if(temp->data==0)
count0++;
else if(temp->data==1)
count1++;
else
count2++;
temp=temp->next;
}
//iterating over count of 0s and filling the linked list
while(count0!=0)
{
temp1->data=0;
temp1=temp1->next;
count0--;
}
//iterating over count of 1s and filling the linked list
while(count1!=0)
{
temp1->data=1;
temp1=temp1->next;
count1--;
}
//iterating over count of 2s and filling the linked list
while(count2!=0)
{
temp1->data=2;
temp1=temp1->next;
count2--;
}
}
}
Time Complexity: O(n)
Space Complexity: O(1)
43. Write a function to detect cycle in an undirected graph
Input: n = 4, e = 4 , 0 1, 1 2, 2 3, 3 1
Output: Yes
Explanation: The graph is represented as follows in adjacency list representation:
0->1
1->2
2->3
3->1
From the above representation, we can see that there exists a cycle: 1→2→3→1
//function to run dfs for a given node in the graph
int dfs(int v,vector<int> adj[],vector<int> &visited,vector<int> &rec,int
i,int parent){
int ans=0;
visited[i]=1;
rec[i]=1;
for(auto x : adj[i]){
if(x!=parent) {
if(rec[x])
return 1;
ans=dfs(v,adj,visited,rec,x,i);
if(ans)
return 1;
}
}
rec[i]=0;
return 0;
}
// Function to detect cycle in an undirected graph.
// it takes adjacency list representation as an argument
bool isCycle(int v, vector<int> adj[]) {
vector<int> visited(v,0),rec(v,0);
int ans=0;
for(int i=0;i<v;i++){
if(visited[i]==0)
ans=dfs(v,adj,visited,rec,i,-1);
if(ans)
return 1;
}
return 0;
}
Time Complexity: O(V+E)
Space Complexity: O(V)
44. Write a function to convert an infix expression to postfix expression
Input: a+b*(c^d)
Output: abcd^*+
int prec(char c)
{
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
public:
// Function to convert an infix expression to a postfix expression.
string infixToPostfix(string s) {
stack<char> st; // For stack operations, we are using C++ built in
stack
string result;
// If an operator is scanned
else {
while (!st.empty()
&& prec(s[i]) <= prec(st.top())) {
if (c == '^' && st.top() == '^')
break;
else {
result += st.top();
st.pop();
}
}
st.push(c);
}
}
return result;
}
Time Complexity: O(n)
Space Complexity: O(n)
45. Write a function to find the maximum for each and every contiguous
subarray of size k.
Input: N = 9, K = 3 arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}
Output: {3, 3, 4, 5, 5, 5, 6}
Explanation: In the first subarray of size 3: {1,2,3}, the value 3 is maximum, similarly for
all such subarrays for size 3.
//function to find maximum in each subarray using sliding window approach
vector<int> max_of_subarrays(vector<int> arr, int n, int k){
int i=0,j=0;
deque<int> dq;
dq.push_front(i++);
while(i<k)
{
while(!dq.empty()&&arr[dq.back()]<=arr[i])
dq.pop_back();
dq.push_back(i++);
}
vector<int> ans;
while(i<n)
{
ans.push_back(arr[dq.front()]);
while(!dq.empty()&&j>=dq.front())
{
dq.pop_front();
}
j++;
while(!dq.empty()&&arr[dq.back()]<=arr[i])
dq.pop_back();
dq.push_back(i++);
}
ans.push_back(arr[dq.front()]);
return ans;
}
Time Complexity: O(n)
Space Complexity: O(k)
46. Write a function to merge two sorted binary search tree
Input:
First BST
7
/ \
5 9
Second BST
4
/ \
3 12
Output: 3 4 5 6 7 9 12
//Function to return a list of integers denoting the node
//values of both the BST in a sorted order.
void inorder(Node*root,vector<int>&v){
if(root==NULL)
return;
inorder(root->left,v);
v.push_back(root->data);
inorder(root->right,v);
}
vector<int> merge(vector<int>v1,vector<int>v2){
vector<int>v;
int n1=v1.size(),n2=v2.size(),i=0,j=0;
while(i<n1&&j<n2){
if(v1[i]>v2[j]){
v.push_back(v2[j]);
j++;
}
else{
v.push_back(v1[i]);
i++;
}
}
while(i<n1){
v.push_back(v1[i]);
i++;
}
while(j<n2){
v.push_back(v2[j]);
j++;
}
return v;
}
vector<int> merge(Node *root1, Node *root2)
{
vector<int>v1,v2;
inorder(root1,v1);
inorder(root2,v2);
return merge(v1,v2);
}
Time Complexity: O(m+n)
Space Complexity: O(height of the first tree + height of the second tree)
47. Write a function to print all unique rows of the given matrix.
Input:
{{1, 1, 1, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 1, 1, 0, 0}}
Output:
{{1, 1, 1, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0}}
vector<vector<int>> uniqueRow(int M[MAX][MAX],int row,int col)
{
set<vector<int>> st;
vector<vector<int>> v;
return v;
}
Time Complexity: O( ROW x COL )
Space Complexity: O( ROW )
48. Write a function to find number of subarrays with product less than
K
Input: arr = [1, 6, 2, 3, 2, 1], k = 12
Output: 11
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int ans=0;
int pdt=1;
int left=0,right=0;
while(right<=nums.size()-1){
pdt*=nums[right];
while(pdt>=k and left<nums.size()){
pdt/=nums[left];
left++;
}
if(right-left>=0)
ans+=right-left+1;//since on adding a new element new subarrays
formed is r-i+1;
right++;
}
return ans;
}
Time Complexity: O(n)
Space Complexity: O(1)
49. Find the subsequence of length 3 with the highest product from a
sequence of non-negative integers, with the elements in increasing
order.
Input: n = 8 arr[ ] = {6, 7, 10, 1, 2, 3, 11, 12}
Output: {10, 11, 12}
The three increasing elements of the given arrays are 10, 11, and 12, which form a
three-size subsequence with the highest product.
vector<int> maxProductSubsequence(int *a , int n)
{
set<int> s;
long long largestOnLeft[n];
for(int i=0;i<n;i++)
{
s.insert(a[i]);
auto it=s.lower_bound(a[i]);
if(it==s.begin())
{
largestOnLeft[i]=-1;
continue;
}
it--;
largestOnLeft[i]=*it;
}
int m=0;
long long p=INT_MIN;
vector<int> result(3);
result[0]=-1;
for(int i=n-1;i>=0;i--)
{
if(a[i]>=m){
m=a[i];}
else
{
if(largestOnLeft[i] !=-1)
{
if(largestOnLeft[i]*a[i]*m >p)
{
p=largestOnLeft[i]*a[i]*m;
result[0]=largestOnLeft[i];
result[1]=a[i];
result[2]=m;
}
}
}
}
return v;
}
Time Complexity: O(nlog(n))
Space Complexity: O(n)
50. Write a function to implement Quicksort on Doubly Linked List
Input: 8<->10<->1<->7<->6
Output: 1<->6<->7<->8<->10
class Solution{
public:
Node* partition(Node *l, Node *h){
//Your code goes here
Node*temp = h;
Node*tt = l;
Node*first = l;
while(tt != h){
if(tt->data <= temp->data){
swap(first->data, tt->data);
first = first->next;
}
tt = tt -> next;
}
swap(first-> data, h->data);
return first;
}
};
// return 2nCn/(n+1)
return C/(n+1);
}
int cap;
node_t head;
unordered_map<int, node_t*> tbl;
Node(int data) {
this.data = data;
}
}
public class InterviewBit
{
// traverse nodes in pre-order way
public static void leftViewUtil(Node root, int level, HashMap<Integer,
Integer> map)
{
if (root == null) {
return;
}
leftView(root);
}
}
58. Given an m x n 2D grid map of '1’s which represents land and '0’s
that represents water return the number of islands (surrounded by
water and formed by connecting adjacent lands in 2 directions -
vertically or horizontally).
Assume that the boundary cases - which are all four edges of the grid
are surrounded by water.
Constraints are:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] can only be ‘0’ or ‘1’.
Example:
Input: grid = [
[“1” , “1” , “1” , “0” , “0”],
[“1” , “1” , “0” , “0” , “0”],
[“0” , “0” , “1” , “0” , “1”],
[“0” , “0” , “0” , “1” , “1”]
]
Output: 3
class InterviewBit {
public int numberOfIslands(char[][] grid) {
if(grid==null || grid.length==0||grid[0].length==0)
return 0;
int m = grid.length;
int n = grid[0].length;
int count=0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j]=='1'){
count++;
mergeIslands(grid, i, j);
}
}
}
return count;
}
if(i<0||i>=m||j<0||j>=n||grid[i][j]!='1')
return;
grid[i][j]='X';
Conclusion
In this post, we covered the most important and frequently asked Data Structures
interview questions. We've also included some pointers and tricks to help you prepare
for the interview. When preparing for the product-based companies interview, keep in
mind that the Data Structures interview is a critical component of the process. It is
critical that you are well prepared for the interview because it will determine whether
or not you are hired. As a result, it is critical to begin planning as soon as possible.
Additional Interview Resources
Programming: DSA - https://www.interviewbit.com/courses/programming/
Data Structure MCQ - https://www.interviewbit.com/data-structure-mcq/
Best Books for Data Structures and Algorithms
- https://www.interviewbit.com/blog/data-structures-and-algorithms-books/
Best Data Structures and Algorithms Course - https://www.interviewbit.com/blog/best-
courses-for-data-structures-and-algorithms/
Algorithm Interview Questions - https://www.interviewbit.com/algorithm-interview-
questions/
Master Data Structures and Algorithms With the Scaler Academy Program
- https://www.scaler.com/courses/data-structures-and-algorithms/
Download PDF
4. What is SQL?
SQL stands for Structured Query Language. It is the standard language for relational
database management systems. It is especially useful in handling organized data
comprised of entities (variables) and relations between different entities of the data.
5. What is the difference between SQL and MySQL?
SQL is a standard language for retrieving and manipulating structured databases. On
the contrary, MySQL is a relational database management system, like SQL Server,
Oracle or IBM DB2, that is used to manage SQL databases.
6. What are Tables and Fields?
A table is an organized collection of data stored in the form of rows and columns.
Columns can be categorized as vertical and rows as horizontal. The columns in a table
are called fields while the rows can be referred to as records.
7. What are Constraints in SQL?
Constraints are used to specify the rules concerning data in the table. It can be applied
for single or multiple fields in an SQL table during the creation of the table or after
creating using the ALTER TABLE command. The constraints are:
NOT NULL - Restricts NULL value from being inserted into a column.
CHECK - Verifies that all values in a field satisfy a condition.
DEFAULT - Automatically assigns a default value if no value has been specified for the
field.
UNIQUE - Ensures unique values to be inserted into the field.
INDEX - Indexes a field providing faster retrieval of records.
PRIMARY KEY - Uniquely identifies each record in a table.
FOREIGN KEY - Ensures referential integrity for a record in another table.
8. What is a Primary Key?
The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain
UNIQUE values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is
comprised of single or multiple fields (columns).
CREATE TABLE Students ( /* Create table with a single field as primary key
*/
ID INT NOT NULL
Name VARCHAR(255)
PRIMARY KEY (ID)
);
Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields
'col_b, col_c'.
Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that references 'col_pk'
in 'table_x'.
Practice Problems
Solve these problems to ace this concept
Engineers Joined
Easy
20.2 Mins
Solve
Job Offer
Hard
22.30 Mins
Solve
Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1' from
table_1 & 'col_2' from table_2 respectively. Do not use alias.
Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1' and
'Table_2', on columns 'Col_1' and 'Col_2' respectively.
Write a SQL query to select the field "app_id" in table "applications" where "app_id" less
than 1000.
Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is equal to
the above collection of "app_id".
Practice Problems
Solve these problems to ace this concept
Study Selection
Medium
8.30 Mins
Solve
Hard
18.8 Mins
Solve
Practice Problems
Solve these problems to ace this concept
Student Query
Easy
7.4 Mins
Solve
Country Filtration
Easy
5.38 Mins
Solve
20. What are some common clauses used with SELECT query in SQL?
Some common SQL clauses used in conjuction with a SELECT query are as follows:
WHERE clause in SQL is used to filter records that are necessary, based on specific
conditions.
ORDER BY clause in SQL is used to sort the records based on some field(s) in
ascending (ASC) or descending order (DESC).
SELECT *
FROM myDB.students
WHERE graduation_year = 2019
ORDER BY studentID DESC;
GROUP BY clause in SQL is used to group records with identical data and can be used
in conjunction with some aggregation functions to produce summarized results from
the database.
HAVING clause in SQL is used to filter records in combination with the GROUP BY
clause. It is different from WHERE, since the WHERE clause cannot filter aggregated
records.
SELECT COUNT(studentId), country
FROM myDB.students
WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;
Write a SQL query to fetch "names" that are present in "accounts" but not in table
"registry".
Write a SQL query to fetch "names" from table "contacts" that are neither present in
"accounts.name" nor in "registry.name".
Amanora Park Town Until the Day I Die (Emily Carpenter), Inception
Sara Ms.
94 (Christopher Nolan)
Ansh 62nd Sector A-10 The Alchemist (Paulo Coelho), Inferno (Dan Brown) Mr.
As we can observe, the Books Issued field has more than one value per record, and to
convert it into 1NF, this has to be resolved into separate individual records for each
book issued. Check the following table in 1NF form -
Students Table (1st Normal Form)
Student Address Books Issued Salutation
Sara Amanora Park Town 94 Until the Day I Die (Emily Carpenter) Ms.
Sara 24th Street Park Avenue Beautiful Bad (Annie Ward) Mrs.
1 Ms.
2 Mr.
3 Mrs.
Write a SQL query to remove first 1000 records from table 'Temporary' based on 'id'.
Write a SQL statement to delete the table 'Temporary' while keeping its relations intact.
31. What is the difference between DROP and TRUNCATE statements?
If a table is dropped, all things associated with the tables are dropped as well. This
includes - the relationships defined on the table with other tables, the integrity checks
and constraints, access privileges and other grants that the table has. To create and
use the table again in its original form, all these relations, checks, constraints,
privileges and relationships need to be redefined. However, if a table is truncated,
none of the above problems exist and the table retains its original structure.
32. What is the difference between DELETE and TRUNCATE statements?
The TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
The DELETE command deletes only the rows from the table based on the condition
given in the where clause or deletes all the rows from the table if no condition is
specified. But it does not free the space containing the table.
33. What are Aggregate and Scalar functions?
An aggregate function performs operations on a collection of values to return a single
scalar value. Aggregate functions are often used with the GROUP BY and HAVING
clauses of the SELECT statement. Following are the widely used SQL aggregate
functions:
AVG() - Calculates the mean of a collection of values.
COUNT() - Counts the total number of records in a specific table or view.
MIN() - Calculates the minimum of a collection of values.
MAX() - Calculates the maximum of a collection of values.
SUM() - Calculates the sum of a collection of values.
FIRST() - Fetches the first element in a collection of values.
LAST() - Fetches the last element in a collection of values.
Note: All aggregate functions described above ignore NULL values except for the
COUNT function.
A scalar function returns a single value based on the input value. Following are the
widely used SQL scalar functions:
LEN() - Calculates the total length of the given field (column).
UCASE() - Converts a collection of string values to uppercase characters.
LCASE() - Converts a collection of string values to lowercase characters.
MID() - Extracts substrings from a collection of string values in a table.
CONCAT() - Concatenates two or more strings.
RAND() - Generates a random collection of numbers of a given length.
ROUND() - Calculates the round-off integer value for a numeric field (or decimal point
values).
NOW() - Returns the current date & time.
FORMAT() - Sets the format to display a collection of values.
34. What is User-defined function? What are its various types?
The user-defined functions in SQL are like functions in any other programming
language that accept parameters, perform complex calculations, and return a value.
They are written to use the logic repetitively whenever required. There are two types of
SQL user-defined functions:
Scalar Function: As explained earlier, user-defined scalar functions return a single scalar
value.
Table-Valued Functions: User-defined table-valued functions return a table as output.
o Inline: returns a table data type based on a single SELECT statement.
o Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT
statements can be used inside the function body.
35. What is OLTP?
OLTP stands for Online Transaction Processing, is a class of software applications
capable of supporting transaction-oriented programs. An essential attribute of an
OLTP system is its ability to maintain concurrency. To avoid single points of failure,
OLTP systems are often decentralized. These systems are usually designed for a large
number of users who conduct short transactions. Database queries are usually simple,
require sub-second response times, and return relatively few records. Here is an
insight into the working of an OLTP system [ Note - The figure is not important for
interviews ] -
36. What are the differences between OLTP and OLAP?
OLTP stands for Online Transaction Processing, is a class of software applications
capable of supporting transaction-oriented programs. An important attribute of an
OLTP system is its ability to maintain concurrency. OLTP systems often follow a
decentralized architecture to avoid single points of failure. These systems are generally
designed for a large audience of end-users who conduct short transactions. Queries
involved in such databases are generally simple, need fast response times, and return
relatively few records. A number of transactions per second acts as an effective
measure for such systems.
OLAP stands for Online Analytical Processing, a class of software programs that are
characterized by the relatively low frequency of online transactions. Queries are often
too complex and involve a bunch of aggregations. For OLAP systems, the effectiveness
measure relies highly on response time. Such systems are widely used for data mining
or maintaining aggregated, historical data, usually in multi-dimensional schemas.
40. How to create empty tables with the same structure as another
table?
Creating empty tables with the same structure can be done smartly by fetching the
records of one table into a new table using the INTO operator while fixing a WHERE
clause to be false for all records. Hence, SQL prepares the new table with a duplicate
structure to accept the fetched records but since no records get fetched due to the
WHERE clause in action, nothing is inserted into the new table.
SELECT * INTO Students_copy
FROM Students WHERE 1 = 2;
46. How can we start, restart and stop the PostgreSQL server?
To start the PostgreSQL server, we run:
service postgresql start
Once the server is successfully started, we get the below message:
Starting PostgreSQL: ok
To restart the PostgreSQL server, we run:
service postgresql restart
Once the server is successfully restarted, we get the message:
Restarting PostgreSQL: server stopped
ok
To stop the server, we run the command:
service postgresql stop
Once stopped successfully, we get the message:
Stopping PostgreSQL: server stopped
ok
60. What can you tell about WAL (Write Ahead Logging)?
Write Ahead Logging is a feature that increases the database reliability by logging
changes before any changes are done to the database. This ensures that we have
enough information when a database crash occurs by helping to pinpoint to what
point the work has been complete and gives a starting point from the point where it
was discontinued.
For more information, you can refer here.
61. What is the main disadvantage of deleting data from an existing
table using the DROP TABLE command?
DROP TABLE command deletes complete data from the table along with removing the
complete table structure too. In case our requirement entails just remove the data,
then we would need to recreate the table to store data in it. In such cases, it is advised
to use the TRUNCATE command.
62. How do you perform case-insensitive searches using regular
expressions in PostgreSQL?
To perform case insensitive matches using a regular expression, we can use
POSIX (~*) expression from pattern matching operators. For example:
'interviewbit' ~* '.*INTervIewBit.*'
A table in SQL must have a primary key associated with it to uniquely identify its records.
Primary key may or may not be unique but can be comprised of multiple fields.
2.
Foreign Key uniquely identifies all the records in the referenced table.
Foreign key may or may not be unique but can be comprised of multiple fields.
3.
What is a Query?
A SELECT or UPDATE statement in SQL.
4.
5.
Which statement is used to update data in the database?
MODIFY
UPDATE
ALTER TABLE
SAVE AS
6.
7.
Sorts the result set in descending order using the DESC keyword.
8.
9.
10.
11.
An SQL query to delete a table from the database and memory while keeping the
structure of the table intact?
DROP TABLE table_name;
12.
INNER JOIN
VIEW
NONE
13.
What is the name of the component that requests data to the PostgreSQL server?
Client
Thin Client
Workstation
Interface
14.
ADD
APPEND
INSERT
15.
What is the order of results shown by default if the ASC or DESC parameter is not
specified with the ORDER BY command?
Results are shown in descending order
16.
Which command is used to tell PostgreSQL to make all changes made to the database
permanent?
Submit
Execute
Apply
Commit
17.
Admin privilege
18.
What command is used for restoring the backup of PostgreSQL which was created
using pg_dump?
psql -R db_dump.psql db_name
19.
What allows us to define how various tables are related to each other formally in a
database?
Views
Database manager
20.
SQL
What languages are supported by PostgreSQL?
PL/pgSQL, PL/Tcl, PL/Perl and PL/Python
Only SQL