0% found this document useful (0 votes)
53 views

Java Interview Questions For Freshers

Java utilizes stack and heap memory differently. Variables and methods are stored in stack memory, while objects are created in heap memory and referenced from the stack. For example, in a program with an integer array, the main method and printArray method would be in stack memory, while the integer array object would be in heap memory. Java does not use pointers for security and simplicity reasons, instead using references that cannot be directly manipulated like pointers.

Uploaded by

smaranika hota
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Java Interview Questions For Freshers

Java utilizes stack and heap memory differently. Variables and methods are stored in stack memory, while objects are created in heap memory and referenced from the stack. For example, in a program with an integer array, the main method and printArray method would be in stack memory, while the integer array object would be in heap memory. Java does not use pointers for security and simplicity reasons, instead using references that cannot be directly manipulated like pointers.

Uploaded by

smaranika hota
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 219

Java Interview Questions for Freshers

1. Why is Java a platform independent language?


Java language was developed in such a way that it does not depend on any hardware
or software due to the fact that the compiler compiles the code and
then converts it to platform-independent byte code which can be run on multiple
systems.
 The only condition to run that byte code is for the machine to have a runtime
environment (JRE) installed in it
2. Why is Java not a pure object-oriented language?
Java supports primitive data types - byte, boolean, char, short, int, float, long, and
double and hence it is not a pure object-oriented language.
3. Difference between Heap and Stack Memory in java. And how java
utilizes this.
Stack memory is the portion of memory that was assigned to every individual program.
And it was fixed. On the other hand, Heap memory is the portion that was not allocated
to the java program but it will be available for use by the java program when it is
required, mostly during the runtime of the program.
Java Utilizes this memory as -
 When we write a java program then all the variables, methods, etc are stored in
the stack memory.
 And when we create any object in the java program then that object was created
in the heap memory. And it was referenced from the stack memory.
Example- Consider the below java program:
class Main {
public void printArray(int[] array){
for(int i : array)
System.out.println(i);
}
public static void main(String args[]) {
int[] array = new int[10];
printArray(array);
}
}
For this java program. The stack and heap memory occupied by java is -
Main and PrintArray is the method that will be available in the stack area and as well as
the variables declared that will also be in the stack area.
And the Object (Integer Array of size 10) we have created, will be available in the Heap
area because that space will be allocated to the program during runtime.

4. Can java be said to be the complete object-oriented programming


language?
It is not wrong if we claim that java is the complete object-oriented programming
language. Because Everything in Java is under the classes. And we can access that by
creating the objects.
But also if we say that java is not a completely object-oriented programming language
because it has the support of primitive data types like int, float, char, boolean, double,
etc.
Now for the question: Is java a completely object-oriented programming
language? We can say that - Java is not a pure object-oriented programming language,
because it has direct access to primitive data types. And these primitive data types don't
directly belong to the Integer classes.
5. How is Java different from C++?
 C++ is only a compiled language, whereas Java is compiled as well as an
interpreted language.
 Java programs are machine-independent whereas a c++ program can run only in
the machine in which it is compiled.
 C++ allows users to use pointers in the program. Whereas java doesn’t allow it.
Java internally uses pointers.
 C++ supports the concept of Multiple inheritances whereas Java doesn't support
this. And it is due to avoiding the complexity of name ambiguity that causes the
diamond problem.
6. Pointers are used in C/ C++. Why does Java not make use of pointers?
Pointers are quite complicated and unsafe to use by beginner programmers. Java
focuses on code simplicity, and the usage of pointers can make it challenging. Pointer
utilization can also cause potential errors. Moreover, security is also compromised if
pointers are used because the users can directly access memory with the help of
pointers.
Thus, a certain level of abstraction is furnished by not including pointers in Java.
Moreover, the usage of pointers can make the procedure of garbage collection quite
slow and erroneous. Java makes use of references as these cannot be manipulated,
unlike pointers.
7. What do you understand by an instance variable and a local variable?
Instance variables are those variables that are accessible by all the methods in the
class. They are declared outside the methods and inside the class. These variables
describe the properties of an object and remain bound to it at any cost.
All the objects of the class will have their copy of the variables for utilization. If any
modification is done on these variables, then only that instance will be impacted by it,
and all other class instances continue to remain unaffected.
Example:
class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}
Local variables are those variables present within a block, function, or constructor and
can be accessed only inside them. The utilization of the variable is restricted to the block
scope. Whenever a local variable is declared inside a method, the other class methods
don’t have any knowledge about the local variable.
Example:
public void athlete() {
String athleteName;
double athleteSpeed;
int athleteAge;
}

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

13. Briefly explain the concept of constructor overloading


Constructor overloading is the process of creating multiple constructors in the class
consisting of the same name with a difference in the constructor parameters. Depending
upon the number of parameters and their corresponding types, distinguishing of the
different types of constructors is done by the compiler.
class Hospital {
int variable1, variable2;
double variable3;
public Hospital(int doctors, int nurses) {
variable1 = doctors;
variable2 = nurses;
}
public Hospital(int doctors) {
variable1 = doctors;
}
public Hospital(double salaries) {
variable3 = salaries
}
}
Three constructors are defined here but they differ on the basis of parameter type and
their numbers.
14. Define Copy constructor in java.
Copy Constructor is the constructor used when we want to initialize the value to the new
object from the old object of the same class.
class InterviewBit{
String department;
String service;
InterviewBit(InterviewBit ib){
this.departments = ib.departments;
this.services = ib.services;
}
}
Here we are initializing the new object value from the old object value in the
constructor. Although, this can also be achieved with the help of object cloning.
15. Can the main method be Overloaded?
Yes, It is possible to overload the main method. We can create as many overloaded main
methods we want. However, JVM has a predefined calling method that JVM will only call
the main method with the definition of -
public static void main(string[] args)
Consider the below code snippets:
class Main {
public static void main(String args[]) {
System.out.println(" Main Method");
}
public static void main(int[] args){
System.out.println("Overloaded Integer array Main Method");
}
public static void main(char[] args){
System.out.println("Overloaded Character array Main Method");
}
public static void main(double[] args){
System.out.println("Overloaded Double array Main Method");
}
public static void main(float args){
System.out.println("Overloaded float Main Method");
}
}

16. Comment on method overloading and overriding by citing relevant


examples.
In Java, method overloading is made possible by introducing different methods in the
same class consisting of the same name. Still, all the functions differ in the number or
type of parameters. It takes place inside a class and enhances program readability.
The only difference in the return type of the method does not promote method
overloading. The following example will furnish you with a clear picture of it.
class OverloadingHelp {
public int findarea (int l, int b) {
int var1;
var1 = l * b;
return var1;
}
public int findarea (int l, int b, int h) {
int var2;
var2 = l * b * h;
return var2;
}
}
Both the functions have the same name but differ in the number of arguments. The first
method calculates the area of the rectangle, whereas the second method calculates the
area of a cuboid.
Method overriding is the concept in which two methods having the same method
signature are present in two different classes in which an inheritance relationship is
present. A particular method implementation (already present in the base class) is
possible for the derived class by using method overriding.
Let’s give a look at this example:
class HumanBeing {
public int walk (int distance, int time) {
int speed = distance / time;
return speed;
}
}
class Athlete extends HumanBeing {
public int walk(int distance, int time) {
int speed = distance / time;
speed = speed * 2;
return speed;
}
}
Both class methods have the name walk and the same parameters, distance, and time. If
the derived class method is called, then the base class method walk gets overridden by
that of the derived class.
17. A single try block and multiple catch blocks can co-exist in a Java
Program. Explain.
Yes, multiple catch blocks can exist but specific approaches should come prior to the
general approach because only the first catch block satisfying the catch condition is
executed. The given code illustrates the same:
public class MultipleCatch {
public static void main(String args[]) {
try {
int n = 1000, x = 0;
int arr[] = new int[n];
for (int i = 0; i <= n; i++) {
arr[i] = i / x;
}
}
catch (ArrayIndexOutOfBoundsException exception) {
System.out.println("1st block = ArrayIndexOutOfBoundsException");
}
catch (ArithmeticException exception) {
System.out.println("2nd block = ArithmeticException");
}
catch (Exception exception) {
System.out.println("3rd block = Exception");
}
}
}
Here, the second catch block will be executed because of division by 0 (i / x). In case x
was greater than 0 then the first catch block will execute because for loop runs till i = n
and array index are till n-1.
18. Explain the use of final keyword in variable, method and class.
In Java, the final keyword is used as defining something as constant /final and
represents the non-access modifier.
 final variable:
o When a variable is declared as final in Java, the value can’t be modified
once it has been assigned.
o If any value has not been assigned to that variable, then it can be assigned
only by the constructor of the class.
 final method:
o A method declared as final cannot be overridden by its children's classes.
o A constructor cannot be marked as final because whenever a class is
inherited, the constructors are not inherited. Hence, marking it final
doesn't make sense. Java throws compilation error saying - modifier
final not allowed here
 final class:
o No classes can be inherited from the class declared as final. But that final
class can extend other classes for its usage.
19. Do final, finally and finalize keywords have the same function?
All three keywords have their own utility while programming.
Final: If any restriction is required for classes, variables, or methods, the final keyword
comes in handy. Inheritance of a final class and overriding of a final method is restricted
by the use of the final keyword. The variable value becomes fixed after incorporating the
final keyword. Example:
final int a=100;
a = 0; // error
The second statement will throw an error.
Finally: It is the block present in a program where all the codes written inside it get
executed irrespective of handling of exceptions. Example:
try {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}
Finalize: Prior to the garbage collection of an object, the finalize method is called so
that the clean-up activity is implemented. Example:
public static void main(String[] args) {
String example = new String("InterviewBit");
example = null;
System.gc(); // Garbage collector called
}
public void finalize() {
// Finalize called
}

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

public void foo(){


System.out.println("Parent class foo!");
}
}
class Child extends Parent{
private int num = 2;

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

public class DemoClass {


public static void main(String args[]) {
Child demoObject=new Child();
demoObject.foo();
/*
This would print -
Parent class parameterised constructor.
Child class default Constructor
Child class foo!
Parent class foo!
*/
}
}

23. Can the static methods be overloaded?


Yes! There can be two or more static methods in a class with the same name but
differing input parameters.
24. Why is the main method static in Java?
The main method is always static because static members are those methods that
belong to the classes, not to an individual object. So if the main method will not be
static then for every object, It is available. And that is not acceptable by JVM. JVM calls
the main method based on the class name itself. Not by creating the object.
Because there must be only 1 main method in the java program as the execution starts
from the main method. So for this reason the main method is static.
25. Can the static methods be overridden?
 No! Declaration of static methods having the same signature can be done in the
subclass but run time polymorphism can not take place in such cases.
 Overriding or dynamic polymorphism occurs during the runtime, but the static
methods are loaded and looked up at the compile time statically. Hence, these
methods cant be overridden.
26. Difference between static methods, static variables, and static classes
in java.
 Static Methods and Static variables are those methods and variables that
belong to the class of the java program, not to the object of the class. This gets
memory where the class is loaded. And these can directly be called with the help
of class names.
o For example - We have used mathematical functions in the java program
like - max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find
that we call it directly with the class name. Like - Math.max(), Math.min(),
etc. So that is a static method. And Similarly static variables we have used
like (length) for the array to get the length. So that is the static method.
 Static classes - A class in the java program cannot be static except if it is the
inner class. If it is an inner static class, then it exactly works like other static
members of the class.
27. What is the main objective of garbage collection?
The main objective of this process is to free up the memory space occupied by the
unnecessary and unreachable objects during the Java program execution by deleting
those unreachable objects.
 This ensures that the memory resource is used efficiently, but it provides no
guarantee that there would be sufficient memory for the program execution.
28. What is a ClassLoader?
 Java Classloader is the program that belongs to JRE (Java Runtime Environment).
The task of ClassLoader is to load the required classes and interfaces to the JVM
when required.
 Example- To get input from the console, we require the scanner class. And the
Scanner class is loaded by the ClassLoader.
29. What part of memory - Stack or Heap - is cleaned in garbage
collection process?
Heap.
30. What are shallow copy and deep copy in java?
To copy the object's data, we have several methods like deep copy and shallow copy.
Example -
class Rectangle{
int length = 5;
int breadth = 3;
}
Object for this Rectangle class - Rectangle obj1 = new Rectangle();
 Shallow copy - The shallow copy only creates a new reference and points to the
same object. Example - For Shallow copy, we can do this by -
Rectangle obj2 = obj1;
Now by doing this what will happen is the new reference is created with the name obj2
and that will point to the same memory location.
 Deep Copy - In a deep copy, we create a new object and copy the old object
value to the new object. Example -
Rectangle obj3 = new Rectangle();
Obj3.length = obj1.length;
Obj3.breadth = obj1.breadth;
Both these objects will point to the memory location as stated below -
Now, if we change the values in shallow copy then they affect the other reference as
well. Let's see with the help of an example -
class Rectangle
{
int length = 5;
int breadth = 3;
}
public class Main
{
public static void main(String[] args) {
Rectangle obj1 = new Rectangle();
//Shallow Copy
Rectangle obj2 = obj1;

System.out.println(" Before Changing the value of object 1, the


object2 will be - ");
System.out.println(" Object2 Length = "+obj2.length+", Object2
Breadth = "+obj2.breadth);

//Changing the values for object1.


obj1.length = 10;
obj1.breadth = 20;

System.out.println("\n After Changing the value of object 1, the


object2 will be - ");
System.out.println(" Object2 Length = "+obj2.length+", Object2
Breadth = "+obj2.breadth);

}
}
Output -
Before Changing the value of object 1, the object2 will be -
Object2 Length = 5, Object2 Breadth = 3

After Changing the value of object 1, the object2 will be -


Object2 Length = 10, Object2 Breadth = 20
We can see that in the above code, if we change the values of object1, then the
object2 values also get changed. It is because of the reference.
Now, if we change the code to deep copy, then there will be no effect on object2 if it
is of type deep copy. Consider some snippets to be added in the above code.
class Rectangle
{
int length = 5;
int breadth = 3;
}
public class Main
{
public static void main(String[] args) {
Rectangle obj1 = new Rectangle();
//Shallow Copy
Rectangle obj2 = new Rectangle();
obj2.length = obj1.length;
obj2.breadth = obj1.breadth;

System.out.println(" Before Changing the value of object 1, the


object2 will be - ");
System.out.println(" Object2 Length = "+obj2.length+", Object2
Breadth = "+obj2.breadth);

//Changing the values for object1.


obj1.length = 10;
obj1.breadth = 20;
System.out.println("\n After Changing the value of object 1, the
object2 will be - ");
System.out.println(" Object2 Length = "+obj2.length+", Object2
Breadth = "+obj2.breadth);

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

After Changing the value of object 1, the object2 will be -


Object2 Length = 5, Object2 Breadth = 3
Now we see that we need to write the number of codes for this deep copy. So to
reduce this, In java, there is a method called clone().
The clone() will do this deep copy internally and return a new object. And to do this
we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();

Java Intermediate Interview Questions


31. Apart from the security aspect, what are the reasons behind making
strings immutable in Java?
A String is made immutable due to the following reasons:
 String Pool: Designers of Java were aware of the fact that String data type is
going to be majorly used by the programmers and developers. Thus, they
wanted optimization from the beginning. They came up with the notion of
using the String pool (a storage area in Java heap) to store the String literals.
They intended to decrease the temporary String object with the help of sharing.
An immutable class is needed to facilitate sharing. The sharing of the mutable
structures between two unknown parties is not possible. Thus, immutable Java
String helps in executing the concept of String Pool.
 Multithreading: The safety of threads regarding the String objects is an
important aspect in Java. No external synchronization is required if the String
objects are immutable. Thus, a cleaner code can be written for sharing the
String objects across different threads. The complex process of concurrency is
facilitated by this method.
 Collections: In the case of Hashtables and HashMaps, keys are String objects. If
the String objects are not immutable, then it can get modified during the period
when it resides in the HashMaps. Consequently, the retrieval of the desired data
is not possible. Such changing states pose a lot of risks. Therefore, it is quite
safe to make the string immutable.
32. What is a singleton class in Java? And How to implement a singleton
class?
Singleton classes are those classes, whose objects are created only once. And with only
that object the class members can be accessed.
Understand this with the help of an example-:
Consider the water jug in the office and if every employee wants that water then they
will not create a new water jug for drinking water. They will use the existing one with
their own reference as a glass. So programmatically it should be implemented as -
class WaterJug{
private int waterQuantity = 500;
private WaterJug(){}
private WaterJug object = null;

// Method to provide the service of Giving Water.


public int getWater(int quantity){
waterQuantity -= quantity;
return quantity;
}
// Method to return the object to the user.
public static Waterjug getInstance(){
// Will Create a new object if the object is not already created and
return the object.
if(object == null){
object = new WaterJug();
}
return object;
}
}
In the above class, the Constructor is private so we cannot create the object of the
class. But we can get the object by calling the method getInstance(). And the
getInstance is static so it can be called without creating the object. And it returns the
object. Now with that object, we can call getWater() to get the water.
Waterjug glass1 = WaterJug.getInstance();
glass1.getWater(1);
We can get the single object using this getInstance(). And it is static, so it is a thread-
safe singleton class. Although there are many ways to create a thread-safe singleton
class. So thread-safe classes can also be:
 When singletons are written with double-checked locking, they can be thread-
safe.
 We can use static singletons that are initialized during class loading. Like we did
in the above example.
 But the most straightforward way to create a thread-safe singleton is to use
Java enums.
33. Which of the below generates a compile-time error? State the
reason.
1. int[] n1 = new int[0];
2. boolean[] n2 = new boolean[-200];
3. double[] n3 = new double[2241423798];
4. char[] ch = new char[20];
We get a compile-time error in line 3. The error we will get in Line 3 is - integer
number too large. It is because the array requires size as an integer. And Integer
takes 4 Bytes in the memory. And the number (2241423798) is beyond the capacity of
the integer. The maximum array size we can declare is - (2147483647).
Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a
compile-time error. The program will compile fine. But we get the runtime exception in
line 2. The exception is - NegativeArraySizeException.
Here what will happen is - At the time when JVM will allocate the required memory
during runtime then it will find that the size is negative. And the array size can’t be
negative. So the JVM will throw the exception.
34. How would you differentiate between a String, StringBuffer, and a
StringBuilder?
 Storage area: In string, the String pool serves as the storage area. For
StringBuilder and StringBuffer, heap memory is the storage area.
 Mutability: A String is immutable, whereas both the StringBuilder and
StringBuffer are mutable.
 Efficiency: It is quite slow to work with a String. However, StringBuilder is the
fastest in performing operations. The speed of a StringBuffer is more than a
String and less than a StringBuilder. (For example appending a character is
fastest in StringBuilder and very slow in String because a new memory is
required for the new String with appended character.)
 Thread-safe: In the case of a threaded environment, StringBuilder and
StringBuffer are used whereas a String is not used. However, StringBuilder is
suitable for an environment with a single thread, and a StringBuffer is suitable
for multiple threads.
Syntax:
// String
String first = "InterviewBit";
String second = new String("InterviewBit");
// StringBuffer
StringBuffer third = new StringBuffer("InterviewBit");
// StringBuilder
StringBuilder fourth = new StringBuilder("InterviewBit");

35. Using relevant properties highlight the differences between


interfaces and abstract classes.
 Availability of methods: Only abstract methods are available in interfaces,
whereas non-abstract methods can be present along with abstract methods in
abstract classes.
 Variable types: Static and final variables can only be declared in the case of
interfaces, whereas abstract classes can also have non-static and non-final
variables.
 Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract
classes do not promote multiple inheritances.
 Data member accessibility: By default, the class data members of interfaces
are of the public- type. Conversely, the class members for an abstract class can
be protected or private also.
 Implementation: With the help of an abstract class, the implementation of an
interface is easily possible. However, the converse is not true;
Abstract class example:
public abstract class Athlete {
public abstract void walk();
}
Interface example:
public interface Walkable {
void walk();
}

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

52. What is the ‘IS-A ‘ relationship in OOPs java?


‘IS-A’ relationship is another name for inheritance. When we inherit the base class from
the derived class, then it forms a relationship between the classes. So that relationship
is termed an ‘IS-A’ Relationship.
Example - Consider a Television (Typical CRT TV). Now another Smart TV that is
inherited from television class. So we can say that the Smart iv is also a TV. Because
CRT TV things can also be done in the Smart TV.
So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ].
53. Which among String or String Buffer should be preferred when
there are lot of updates required to be done in the data?
StringBuffer is mutable and dynamic in nature whereas String is immutable. Every
updation / modification of String creates a new String thereby overloading the string
pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always
preferred to use StringBuffer as it will reduce the overhead of the creation of multiple
String objects in the string pool.
54. How to not allow serialization of attributes of a class in Java?
 In order to achieve this, the attribute can be declared along with the usage
of transient keyword as shown below:
public class InterviewBitExample {
private transient String someInfo;
private String name;
private int id;
// :
// Getters setters
// :
}
 In the above example, all the fields except someInfo can be serialized.
55. What happens if the static modifier is not included in the main
method signature in Java?
There wouldn't be any compilation error. But then the program is run, since the JVM
cant map the main method signature, the code throws “NoSuchMethodError” error at
the runtime.
56. Consider the below program, identify the output, and also state the
reason for that.
public class Main{
public static void main(String[] args) {
System.out.println(" Hello. Main Method. ");
}
public static void main(int[] args) {
System.out.println(" Hello. Main Method2. ");
}
}
The output of the above program will be Hello. Main Method. This is because JVM
will always call the main method based on the definition it already has. Doesn't matter
how many main methods we overload it will only execute one main method based on
its declaration in JVM.
57. Can we make the main() thread a daemon thread?
In java multithreading, the main() threads are always non-daemon threads. And there
is no way we can change the nature of the non-daemon thread to the daemon thread.
58. What happens if there are multiple main methods inside one class in
Java?
The program can't compile as the compiler says that the method has been already
defined inside the class.
59. What do you understand by Object Cloning and how do you achieve
it in Java?
 It is the process of creating an exact copy of any object. In order to support this, a java
class has to implement the Cloneable interface of java.lang package and override the
clone() method provided by the Object class the syntax of which is:
protected Object clone() throws CloneNotSupportedException{
return (Object)super.clone();
}
 In case the Cloneable interface is not implemented and just the method is overridden,
it results in CloneNotSupportedException in Java.
60. How does an exception propagate in the code?
When an exception occurs, first it searches to locate the matching catch block. In case,
the matching catch block is located, then that block would be executed. Else, the
exception propagates through the method call stack and goes into the caller method
where the process of matching the catch block is performed. This propagation
happens until the matching catch block is found. If the match is not found, then the
program gets terminated in the main method.
Practice Problems
Solve these problems to ace this concept

Exception Handling

Easy

5.9 Mins

Solve

Try Catch Block

Easy

3.36 Mins

Solve

Finally Block

Easy

2.45 Mins

Solve

61. How do exceptions affect the program if it doesn't handle them?


Exceptions are runtime errors. Suppose we are making an android application with
java. And it all works fine but there is an exceptional case when the application tries to
get the file from storage and the file doesn’t exist (This is the case of exception in
java). And if this case is not handled properly then the application will crash. This will
be a bad experience for users. This is the type of error that cannot be controlled by
the programmer. But programmers can take some steps to avoid this so that the
application won’t crash. The proper action can be taken at this step.
62. Is it mandatory for a catch block to be followed after a try block?
No, it is not necessary for a catch block to be present after a try block. - A try block
should be followed either by a catch block or by a finally block. If the exceptions
likelihood is more, then they should be declared using the throws clause of the
method.
63. Will the finally block get executed when the return statement is
written at the end of try block and catch block as shown below?
public int someMethod(int i){
try{
//some statement
return 1;
}catch(Exception e){
//some statement
return 999;
}finally{
//finally block statements
}
}
finally block will be executed irrespective of the exception or not. The only case where
finally block is not executed is when it encounters ‘System.exit()’ method anywhere in
try/catch block.
64. Can you call a constructor of a class inside the another constructor?
Yes, the concept can be termed as constructor chaining and can be achieved
using this().
65. Contiguous memory locations are usually used for storing actual
values in an array but not in ArrayList. Explain.
In the case of ArrayList, data storing in the form of primitive data types (like int, float,
etc.) is not possible. The data members/objects present in the ArrayList have
references to the objects which are located at various sites in the memory. Thus,
storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes
place in various memory locations.
However, the same does not apply to the arrays. Object or primitive type values can be
stored in arrays in contiguous memory locations, hence every element does not
require any reference to the next element.
66. Why does the java array index start with 0?
It is because the 0 index array avoids the extra arithmetic operation to calculate the
memory address.
Example - Consider the array and assume each element takes 4-byte memory space.
Then the address will be like this -

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

Java Interview Questions for Experienced


70. Although inheritance is a popular OOPs concept, it is less
advantageous than composition. Explain.
Inheritance lags behind composition in the following scenarios:
 Multiple-inheritance is not possible in Java. Classes can only extend from one
superclass. In cases where multiple functionalities are required, for example - to read
and write information into the file, the pattern of composition is preferred. The writer,
as well as reader functionalities, can be made use of by considering them as the private
members.
 Composition assists in attaining high flexibility and prevents breaking of encapsulation.
 Unit testing is possible with composition and not inheritance. When a developer wants
to test a class composing a different class, then Mock Object can be created for
signifying the composed class to facilitate testing. This technique is not possible with
the help of inheritance as the derived class cannot be tested without the help of the
superclass in inheritance.
 The loosely coupled nature of composition is preferable over the tightly coupled
nature of inheritance.
Let’s take an example:
package comparison;
public class Top {
public int start() {
return 0;
}
}
class Bottom extends Top {
public int stop() {
return 0;
}
}
In the above example, inheritance is followed. Now, some modifications are done to
the Top class like this:
public class Top {
public int start() {
return 0;
}
public void stop() {
}
}
If the new implementation of the Top class is followed, a compile-time error is bound
to occur in the Bottom class. Incompatible return type is there for the Top.stop()
function. Changes have to be made to either the Top or the Bottom class to ensure
compatibility. However, the composition technique can be utilized to solve the given
problem:
class Bottom {
Top par = new Top();
public int stop() {
par.start();
par.stop();
return 0;
}
}

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;

public class IBDoubleBraceDemo{


public static void main(String[] args){
Set<String> stringSets = new HashSet<String>()
{
{
add("set1");
add("set2");
add("set3");
}
};

doSomething(stringSets);
}

private static void doSomething(Set<String> stringSets){


System.out.println(stringSets);
}
}
In the above example, we see that the stringSets were initialized by using double
braces.
 The first brace does the task of creating an anonymous inner class that has the
capability of accessing the parent class’s behavior. In our example, we are creating the
subclass of HashSet so that it can use the add() method of HashSet.
 The second braces do the task of initializing the instances.
Care should be taken while initializing through this method as the method involves the
creation of anonymous inner classes which can cause problems during the garbage
collection or serialization processes and may also result in memory leaks.
87. Why is it said that the length() method of String class doesn't return
accurate results?
 The length method returns the number of Unicode units of the String. Let's understand
what Unicode units are and what is the confusion below.
 We know that Java uses UTF-16 for String representation. With this Unicode, we need
to understand the below two Unicode related terms:
o Code Point: This represents an integer denoting a character in the code space.
o Code Unit: This is a bit sequence used for encoding the code points. In order to
do this, one or more units might be required for representing a code point.
 Under the UTF-16 scheme, the code points were divided logically into 17 planes and
the first plane was called the Basic Multilingual Plane (BMP). The BMP has classic
characters - U+0000 to U+FFFF. The rest of the characters- U+10000 to U+10FFFF were
termed as the supplementary characters as they were contained in the remaining
planes.
o The code points from the first plane are encoded using one 16-bit code unit
o The code points from the remaining planes are encoded using two code units.
Now if a string contained supplementary characters, the length function would count
that as 2 units and the result of the length() function would not be as per what is
expected.
In other words, if there is 1 supplementary character of 2 units, the length of that
SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the
java documentation, it is expected, but as per the real logic, it is inaccurate.
88. What is the output of the below code and why?
public class InterviewBit{
public static void main(String[] args)
{
System.out.println('b' + 'i' + 't');
}
}
“bit” would have been the result printed if the letters were used in double-quotes (or
the string literals). But the question has the character literals (single quotes) being
used which is why concatenation wouldn't occur. The corresponding ASCII values of
each character would be added and the result of that sum would be printed.
The ASCII values of ‘b’, ‘i’, ‘t’ are:
 ‘b’ = 98
 ‘i’ = 105
 ‘t’ = 116
98 + 105 + 116 = 319
Hence 319 would be printed.
89. What are the possible ways of making object eligible for garbage
collection (GC) in Java?
First Approach: Set the object references to null once the object creation purpose is
served.
public class IBGarbageCollect {
public static void main (String [] args){
String s1 = "Some String";
// s1 referencing String object - not yet eligible for GC
s1 = null; // now s1 is eligible for GC
}
}
Second Approach: Point the reference variable to another object. Doing this, the
object which the reference variable was referencing before becomes eligible for GC.
public class IBGarbageCollect {
public static void main(String [] args){
String s1 = "To Garbage Collect";
String s2 = "Another Object";
System.out.println(s1); // s1 is not yet eligible for GC
s1 = s2; // Point s1 to other object pointed by s2
/* Here, the string object having the content "To Garbage Collect" is
not referred by any reference variable. Therefore, it is eligible for GC */
}
}
Third Approach: Island of Isolation Approach: When 2 reference variables pointing to
instances of the same class, and these variables refer to only each other and the
objects pointed by these 2 variables don't have any other references, then it is said to
have formed an “Island of Isolation” and these 2 objects are eligible for GC.
public class IBGarbageCollect {
IBGarbageCollect ib;
public static void main(String [] str){
IBGarbageCollect ibgc1 = new IBGarbageCollect();
IBGarbageCollect ibgc2 = new IBGarbageCollect();
ibgc1.ib = ibgc2; //ibgc1 points to ibgc2
ibgc2.ib = ibgc1; //ibgc2 points to ibgc1
ibgc1 = null;
ibgc2 = null;
/*
* We see that ibgc1 and ibgc2 objects refer
* to only each other and have no valid
* references- these 2 objects for island of isolcation - eligible for
GC
*/
}
}

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

num[2] = new int[5];


num[0] = new int[4];
num[1] = new int[3];

num = new int[2][];


}
}
In the above program, a total of 7 objects will be eligible for garbage collection. Let’s
visually understand what's happening in the code.
In the above figure on line 3, we can see that on each array index we are declaring a
new array so the reference will be of that new array on all the 3 indexes. So the old
array will be pointed to by none. So these three are eligible for garbage collection.
And on line 4, we are creating a new array object on the older reference. So that will
point to a new array and older multidimensional objects will become eligible for
garbage collection.
91. What is the best way to inject dependency? Also, state the reason.
There is no boundation for using a particular dependency injection. But the
recommended approach is -
Setters are mostly recommended for optional dependencies injection, and constructor
arguments are recommended for mandatory ones. This is because constructor
injection enables the injection of values into immutable fields and enables reading
them more easily.
92. How we can set the spring bean scope. And what supported scopes
does it have?
A scope can be set by an annotation such as the @Scope annotation or the "scope"
attribute in an XML configuration file. Spring Bean supports the following five scopes:
 Singleton
 Prototype
 Request
 Session
 Global-session
93. What are the different categories of Java Design patterns?
Java Design patterns are categorized into the following different types. And those are
also further categorized as
Structural patterns:
 Adapter
 Bridge
 Filter
 Composite
 Decorator
 Facade
 Flyweight
 Proxy
Behavioral patterns:
 Interpreter
 Template method/ pattern
 Chain of responsibility
 Command pattern
 Iterator pattern
 Strategy pattern
 Visitor pattern
J2EE patterns:
 MVC Pattern
 Data Access Object pattern
 Front controller pattern
 Intercepting filter pattern
 Transfer object pattern
Creational patterns:
 Factory method/Template
 Abstract Factory
 Builder
 Prototype
 Singleton
94. What is a Memory Leak? Discuss some common causes of it.
The Java Garbage Collector (GC) typically removes unused objects when they are no
longer required, but when they are still referenced, the unused objects cannot be
removed. So this causes the memory leak problem. Example - Consider a linked list
like the structure below -
In the above image, there are unused objects that are not referenced. But then also
Garbage collection will not free it. Because it is referencing some existing referenced
object. So this can be the situation of memory leak.
Some common causes of Memory leaks are -
 When there are Unbounded caches.
 Excessive page swapping is done by the operating system.
 Improper written custom data structures.
 Inserting into a collection object without first deleting it.
etc.
95. Assume a thread has a lock on it, calling the sleep() method on that
thread will release the lock?
A thread that has a lock won't be released even after it calls sleep(). Despite the thread
sleeping for a specified period of time, the lock will not be released.

Java Programming Interview Questions


96. Check if a given string is palindrome using recursion.
/*
* Java program to check if a given inputted string is palindrome or not
using recursion.
*/
import java.util.*;
public class InterviewBit {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String word = s.nextLine();
System.out.println("Is "+word+" palindrome? -
"+isWordPalindrome(word));
}

public static boolean isWordPalindrome(String word){


String reverseWord = getReverseWord(word);
//if word equals its reverse, then it is a palindrome
if(word.equals(reverseWord)){
return true;
}
return false;
}

public static String getReverseWord(String word){


if(word == null || word.isEmpty()){
return word;
}

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

97. Write a Java Program to print Fibonacci Series using Recursion.


class InterviewBit {
public static void printFibonacci(int val_1, int val_2, int num){
//Base Case
if(num == 0)
return;

//Printing the next Fibonacci number


System.out.print( val_1 + val_2 + " ");

//Recursively calling for printing Fibonacci for remaining length


printFibonacci(val_2, val_1+val_2, --num);
}
public static void main(String args[]) {
System.out.println(" *** Fibonacci Series *** ");

//Printing the first two values


System.out.print("0 1 ");

//Calling Method to print the fibonacci for length 10


printFibonacci(0, 1, 10);
}
}
In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then
based on the length of Fibonacci to be printed, we are using the helper function to
print that.
98. Write a Java program to check if the two strings are anagrams.
The main idea is to validate the length of strings and then if found equal, convert the
string to char array and then sort the arrays and check if both are equal.
import java.util.Arrays;
import java.util.Scanner;
public class InterviewBit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//Input from two strings
System.out.print("First String: ");
String string1 = s.nextLine();
System.out.print("Second String: ");
String string2 = s.nextLine();
// check for the length
if(string1.length() == string2.length()) {
// convert strings to char array
char[] characterArray1 = string1.toCharArray();
char[] characterArray2 = string2.toCharArray();
// sort the arrays
Arrays.sort(characterArray1);
Arrays.sort(characterArray2);
// check for equality, if found equal then anagram, else not an anagram
boolean isAnagram = Arrays.equals(characterArray1, characterArray2);
System.out.println("Anagram: "+ isAnagram);
}
}

99. Write a Java Program to find the factorial of a given number.


public class FindFactorial {
public static void main(String[] args) {
int num = 10;
long factorialResult = 1l;
for(int i = 1; i <= num; ++i)
{
factorialResult *= i;
}
System.out.println("Factorial: "+factorialResult);
}
}

100. Given an array of non-duplicating numbers from 1 to n where one


number is missing, write an efficient java program to find that missing
number.
Idea is to find the sum of n natural numbers using the formula and then finding the
sum of numbers in the given array. Subtracting these two sums results in the number
that is the actual missing number. This results in O(n) time complexity and O(1) space
complexity.
public class IBMissingNumberProblem {

public static void main(String[] args) {

int[] array={4,3,8,7,5,2,6};
int missingNumber = findMissingNum(array);
System.out.println("Missing Number is "+ missingNumber);
}

public static int findMissingNum(int[] array) {


int n=array.length+1;
int sumOfFirstNNums=n*(n+1)/2;
int actualSumOfArr=0;
for (int i = 0; i < array.length; i++) {
actualSumOfArr+=array[i];
}
return sumOfFirstNNums-actualSumOfArr;
}
}

101. Write a Java Program to check if any number is a magic number or


not. A number is said to be a magic number if after doing sum of digits
in each step and inturn doing sum of digits of that sum, the ultimate
result (when there is only one digit left) is 1.
Example, consider the number:
 Step 1: 163 => 1+6+3 = 10
 Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number
public class IBMagicNumber{

public static void main(String[] args) {


int num = 163;
int sumOfDigits = 0;
while (num > 0 || sumOfDigits > 9)
{
if (num == 0)
{
num = sumOfDigits;
sumOfDigits = 0;
}
sumOfDigits += num % 10;
num /= 10;
}

// If sum is 1, original number is magic number


if(sumOfDigits == 1) {
System.out.println("Magic number");
}else {
System.out.println("Not magic number");
}
}
}

102. Write a Java program to create and throw custom exceptions.


class InterviewBit {
public static void main(String args[]) throws CustomException {

// Throwing the custom exception be passing the message


throw new CustomException(" This is my custom Exception ");
}
}
//Creating Custom Exception Class
class CustomException extends Exception{
//Defining Constructor to throw exception message
public CustomException(String message){
super(message);
}
}
We have created the exception class named with CustomException and called the base
exception constructor with the error message that we want to print. And to avoid
handling exceptions in the main method, we have used the throws keyword in the
method declaration.
103. Write a Java program to reverse a string.
class InterviewBit{
public static void main(String[] args){
//Input String
String str = "Welcome to InterviewBit";

//Pointers.
int i = 0, j = str.length()-1;

//Result character array to store the reversed string.


char[] revString = new char[j+1];

//Looping and reversing the string.


while(i < j){
revString[j] = str.charAt(i);
revString[i] = str.charAt(j);
i++;
j--;
}
//Printing the reversed String.
System.out.println("Reversed String = " +
String.valueOf(revString));
}
}
In the above code, we are storing the last character from the string to the first and the
first value to the last in the output character array. And doing the same thing in the
loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.
104. Write a Java program to rotate arrays 90 degree clockwise by
taking matrices from user input.
mport java.util.Scanner;
public class InterviewBit
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int no;
System.out.print("Enter size of Array : ");
no = sc.nextInt();
int[][] a = new int[no][no];
System.out.print("Enter "+ no*no+" Element Array : ");

for(int i = 0; i<no; i++){


for(int j = 0; j<no; j++){
a[i][j] = sc.nextInt();
}
}
System.out.print("\nArray Before Rotation\n\n");
for(int i = 0; i<no; i++){
for(int j = 0; j<no; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}

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

//Reverse Each row


for(int i = 0; i < no; i++){
int l, j;
for(j = 0, l = no -1; j < l; j++){
int temp = a[i][j];
a[i][j] = a[i][l];
a[i][l] = temp;
l--;
}
}

System.out.println("Array After Rotation - \n");

for(int i = 0; i<no; i++){


for(int j = 0; j<no; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
In the above code, for rotating the matrix to 90 degrees we are first transposing the
matrix so the row becomes the column. And after that, we are reversing each row in
the matrix. So this is how the matrix got rotated.
105. Write a java program to check if any number given as input is the
sum of 2 prime numbers.
Example :
Input - 18
Output -
18 = 13 + 5
18 = 11 + 7
public class InterviewBit
{
// Method to Check Prime Number
private static int check_prime(int num){
int flag = 0;
for(int i = 2; i<=num/2; i++){
if(num%i == 0){
flag = 1;
return 1;
}
}
if(flag == 0)
return 0;
return 1;
}
// Method to get print the prime sum
private static void find(int num){
for(int i = 2; i <= num/2; i++){
if(check_prime(i) == 0){
if(check_prime(num-i) == 0)
System.out.println(num + " = "+ (num-i) + " "+ i);
}
}
}
public static void main(String[] args) {
find(18);
}
}
In the above code, for any number n, we find all the 2 pairs of numbers that are added
together resulting in n. And each checking number if it is prime. If it is prime then we
are printing that.
106. Write a Java program for solving the Tower of Hanoi Problem.
public class InterviewBit
{
//Recursive Method for Solving the Tower of hanoi.
private static void TOH(char source, char auxiliary, char destination,
int numOfDisk){
if (numOfDisk > 0){
TOH(source, destination, auxiliary, numOfDisk-1);
System.out.println("Move 1 disk from "+source+" to
"+destination+" using "+auxiliary+".");
TOH(auxiliary, source, destination, numOfDisk-1);
}
}
public static void main(String[] args) {
TOH('A','B','C', 3);
}
}
In the above code we are first moving the n-1 disk from Tower A to Tower B, then
moving that nth disk from Tower A to Tower C, and finally, the remaining n-1 disk
from Tower B to Tower C. And we are doing this recursively for the n-1 disk.
107. Implement Binary Search in Java using recursion.
public class Main
{
//Recursive method for binary search
private static boolean binarySearch(int[] arr, int low, int high, int
key){

//Calculating Mid.
int mid = (low + high)/2;

//Base Case.
if(low > high)
return false;

//Checking if the key is found in the middle.


if(arr[mid] == key)
return true;

//Searching on the left half if a key exists there.


if(key < arr[mid])
return binarySearch(arr, low, mid-1, key);

//Searching on the other half otherwise.


return binarySearch(arr, mid+1, high, key);
}
public static void main(String[] args) {

int[] arr = {2, 5, 9, 13, 17, 21, 30};


if(binarySearch(arr, 0, (arr.length-1), 30))
System.out.println(" Element Found. ");
else
System.out.println(" Element not Found.");
}
}
In the above code, we are finding the middle element each time and checking if the
element is in the middle or not. If it is not, then we check on which side from the
middle it exists. And Recursively searching on the particular subarray. So this way we
are reducing the search space by 2 every time. So the search time is very low.
Conclusion
108. Conclusion
Java is one of the simple high-level languages that provides powerful tools and
impressive standards required for application development. It was also one of the first
languages to provide amazing threading support for tackling concurrency-based
problems. The easy-to-use syntax and the built-in features of Java combined with the
stability it provides to applications are the main reasons for this language to have
ever-growing usage in the software community.

Basic Data Structure Interview Questions for Freshers


1. What are Data Structures?
A data structure is a mechanical or logical way that data is organized within a program.
The organization of data is what determines how a program performs. There are many
types of data structures, each with its own uses. When designing code, we need to pay
particular attention to the way data is structured. If data isn't stored efficiently or
correctly structured, then the overall performance of the code will be reduced.
2. Why Create Data Structures?
Data structures serve a number of important functions in a program. They ensure that
each line of code performs its function correctly and efficiently, they help the
programmer identify and fix problems with his/her code, and they help to create a clear
and organized code base.
3. What are some applications of Data structures?
Following are some real-time applications of data structures:
 Decision Making
 Genetics
 Image Processing
 Blockchain
 Numerical and Statistical Analysis
 Compiler Design
 Database Design and many more
You can download a PDF version of Data Structure Interview Questions.
Download PDF

4. Explain the process behind storing a variable in memory.


 A variable is stored in memory based on the amount of memory that is needed.
Following are the steps followed to store a variable:
o The required amount of memory is assigned first.
o Then, it is stored based on the data structure being used.
 Using concepts like dynamic allocation ensures high efficiency and that the storage units
can be accessed based on requirements in real-time.
5. Can you explain the difference between file structure and storage
structure?
 File Structure: Representation of data into secondary or auxiliary memory say any
device such as a hard disk or pen drives that stores data which remains intact until
manually deleted is known as a file structure representation.
 Storage Structure: In this type, data is stored in the main memory i.e RAM, and is
deleted once the function that uses this data gets completely executed.
The difference is that the storage structure has data stored in the memory of the
computer system, whereas the file structure has the data stored in the auxiliary memory.
6. Describe the types of Data Structures?
 Linear Data Structure: A data structure that includes data elements arranged
sequentially or linearly, where each element is connected to its previous and next nearest
elements, is referred to as a linear data structure. Arrays and linked lists are two
examples of linear data structures.
 Non-Linear Data Structure: Non-linear data structures are data structures in which data
elements are not arranged linearly or sequentially. We cannot walk through all elements
in one pass in a non-linear data structure, as in a linear data structure. Trees and graphs
are two examples of non-linear data structures.
7. What is a stack data structure? What are the applications of stack?
A stack is a data structure that is used to represent the state of an application at a
particular point in time. The stack consists of a series of items that are added to the top
of the stack and then removed from the top. It is a linear data structure that follows a
particular order in which operations are performed. LIFO (Last In First Out) or FILO (First
In Last Out) are two possible orders. A stack consists of a sequence of items. The
element that's added last will come out first, a real-life example might be a stack of
clothes on top of each other. When we remove the cloth that was previously on top, we
can say that the cloth that was added last comes out first.
Following are some applications for stack data structure:
 It acts as temporary storage during recursive operations
 Redo and Undo operations in doc editors
 Reversing a string
 Parenthesis matching
 Postfix to Infix Expressions
 Function calls order
8. What are different operations available in stack data structure?
Some of the main operations provided in the stack data structure are:
 push: This adds an item to the top of the stack. The overflow condition occurs if the
stack is full.
 pop: This removes the top item of the stack. Underflow condition occurs if the stack is
empty.
 top: This returns the top item from the stack.
 isEmpty: This returns true if the stack is empty else false.
 size: This returns the size of the stack.
9. What is a queue data structure? What are the applications of queue?
A queue is a linear data structure that allows users to store items in a list in a systematic
manner. The items are added to the queue at the rear end until they are full, at which
point they are removed from the queue from the front. Queues are commonly used in
situations where the users want to hold items for a long period of time, such as during a
checkout process. A good example of a queue is any queue of customers for a resource
where the first consumer is served first.
Following are some applications of queue data structure:
 Breadth-first search algorithm in graphs
 Operating system: job scheduling operations, Disk scheduling, CPU scheduling etc.
 Call management in call centres
10. What are different operations available in queue data structure?
 enqueue: This adds an element to the rear end of the queue. Overflow conditions occur
if the queue is full.
 dequeue: This removes an element from the front end of the queue. Underflow
conditions occur if the queue is empty.
 isEmpty: This returns true if the queue is empty or else false.
 rear: This returns the rear end element without removing it.
 front: This returns the front-end element without removing it.
 size: This returns the size of the queue.
11. Differentiate between stack and queue data structure.
Stack Queue

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.

Stack is based on LIFO(Last In First Out)


Queue is based on FIFO(First In First Out) principle
principle

Insertion operation in Stack is known as


Insertion operation in Queue is known as eneque.
push.

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

Used in solving recursion problems Used in solving sequential processing problems

Practice Problems
Solve these problems to ace this concept

Evaluate Expression

Easy

32.46 Mins

Solve

Level Order

Easy

29.55 Mins

Solve

12. How to implement a queue using stack?


A queue can be implemented using two stacks. Let q be the queue
andstack1 and stack2 be the 2 stacks for implementing q. We know that stack supports
push, pop, and peek operations and using these operations, we need to emulate the
operations of the queue - enqueue and dequeue. Hence, queue q can be implemented
in two methods (Both the methods use auxillary space complexity of O(n)):
1. By making enqueue operation costly:
 Here, the oldest element is always at the top of stack1 which ensures dequeue
operation occurs in O(1) time complexity.
 To place the element at top of stack1, stack2 is used.
 Pseudocode:
o Enqueue: Here time complexity will be O(n)
enqueue(q, data):
While stack1 is not empty:
Push everything from stack1 to stack2.
Push data to stack1
Push everything back to stack1.
 Dequeue: Here time complexity will be O(1)
deQueue(q):
If stack1 is empty then error else
Pop an item from stack1 and return it
2. By making the dequeue operation costly:
 Here, for enqueue operation, the new element is pushed at the top of stack1. Here, the
enqueue operation time complexity is O(1).
 In dequeue, if stack2 is empty, all elements from stack1 are moved to stack2 and top
of stack2 is the result. Basically, reversing the list by pushing to a stack and returning
the first enqueued element. This operation of pushing all elements to a new stack takes
O(n) complexity.
 Pseudocode:
o Enqueue: Time complexity: O(1)
enqueue(q, data):
Push data to stack1
 Dequeue: Time complexity: O(n)
dequeue(q):
If both stacks are empty then raise error.
If stack2 is empty:
While stack1 is not empty:
push everything from stack1 to stack2.
Pop the element from stack2 and return it.

13. How do you implement stack using queues?


 A stack can be implemented using two queues. We know that a queue supports enqueue
and dequeue operations. Using these operations, we need to develop push, pop
operations.
 Let stack be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Then, stack ‘s’ can be
implemented in two ways:
1. By making push operation costly:
 This method ensures that the newly entered element is always at the front of ‘q1’ so that
pop operation just dequeues from ‘q1’.
 ‘q2’ is used as auxillary queue to put every new element in front of ‘q1’ while ensuring
pop happens in O(1) complexity.
 Pseudocode:
o Push element to stack s: Here push takes O(n) time complexity.
push(s, data):
Enqueue data to q2
Dequeue elements one by one from q1 and enqueue to q2.
Swap the names of q1 and q2
 Pop element from stack s: Takes O(1) time complexity.
pop(s):
dequeue from q1 and return it.
2. By making pop operation costly:
 In push operation, the element is enqueued to q1.
 In pop operation, all the elements from q1 except the last remaining element, are
pushed to q2 if it is empty. That last element remaining of q1 is dequeued and returned.
 Pseudocode:
o Push element to stack s: Here push takes O(1) time complexity.
push(s,data):
Enqueue data to q1
 Pop element from stack s: Takes O(n) time complexity.
pop(s):
Step1: Dequeue every elements except the last element from q1 and
enqueue to q2.
Step2: Dequeue the last item of q1, the dequeued item is stored in
result variable.
Step3: Swap the names of q1 and q2 (for getting updated data after
dequeue)
Step4: Return the result.

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

Max Sum Contiguous Subarray

Easy

33.39 Mins

+4

Solve

15. Elaborate on different types of array data structure


There are several different types of arrays:
 One-dimensional array: A one-dimensional array stores its elements in contiguous
memory locations, accessing them using a single index value. It is a linear data
structure holding all the elements in a sequence.
 Two-dimensional array: A two-dimensional array is a tabular array that includes rows
and columns and stores data. An M × N two-dimensional array is created by grouping
M rows and N columns into N columns and rows.
 Three-dimensional array: A three-dimensional array is a grid that has rows, columns,
and depth as a third dimension. It comprises a cube with rows, columns, and depth as
a third dimension. The three-dimensional array has three subscripts for a position in a
particular row, column, and depth. Depth (dimension or layer) is the first index, row
index is the second index, and column index is the third index.
16. What is a linked list data structure? What are the applications for the
Linked list?
A linked list can be thought of as a series of linked nodes (or items) that are connected
by links (or paths). Each link represents an entry into the linked list, and each entry
points to the next node in the sequence. The order in which nodes are added to the
list is determined by the order in which they are created.
Following are some applications of linked list data structure:
 Stack, Queue, binary trees, and graphs are implemented using linked lists.
 Dynamic management for Operating System memory.
 Round robin scheduling for operating system tasks.
 Forward and backward operation in the browser.
17. Elaborate on different types of Linked List data structures?
Following are different types of linked lists:
1. Singly Linked List: A singly linked list is a data structure that is used to store
multiple items. The items are linked together using the key. The key is used to identify
the item and is usually a unique identifier. In a singly linked list, each item is stored in a
separate node. The node can be a single object or it can be a collection of objects.
When an item is added to the list, the node is updated and the new item is added to
the end of the list. When an item is removed from the list, the node that contains the
removed item is deleted and its place is taken by another node. The key of a singly
linked list can be any type of data structure that can be used to identify an object. For
example, it could be an integer, a string, or even another singly linked list. Singly-
linked lists are useful for storing many different types of data. For example, they are
commonly used to store lists of items such as grocery lists or patient records. They are
also useful for storing data that is time sensitive such as stock market prices or flight
schedules.
2. Doubly Linked List: A doubly linked list is a data structure that allows for two-way
data access such that each node in the list points to the next node in the list and also
points back to its previous node. In a doubly linked list, each node can be accessed by
its address, and the contents of the node can be accessed by its index. It's ideal for
applications that need to access large amounts of data in a fast manner. A
disadvantage of a doubly linked list is that it is more difficult to maintain than a single-
linked list. In addition, it is more difficult to add and remove nodes than in a single-
linked list.

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

A linked list is a collection of entities known as nodes.


An array is a collection of data elements
The node is divided into two sections: data and
of the same type.
address.

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.

An array's elements are not dependent


Linked List elements are dependent on one another.
on one another.

It is easier and faster to access an


In the linked list, it takes time to access an element.
element in an array.

Memory utilization is ineffective in the


Memory utilization is effective in the case of linked lists.
case of an array.

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

19. What is an asymptotic analysis of an algorithm?


Asymptotic analysis of an algorithm defines the run-time performance as per its
mathematical boundations. Asymptotic analysis helps us articulate the best
case(Omega Notation, Ω), average case(Theta Notation, θ), and worst case(Big Oh
Notation, Ο) performance of an algorithm.
20. What is hashmap in data structure?
Hashmap is a data structure that uses an implementation of a hash table data
structure which allows access to data in constant time (O(1)) complexity if you have the
key.
21. What is the requirement for an object to be used as key or value in
HashMap?
 The key or value object that gets used in the hashmap must
implement equals() and hashcode() method.
 The hash code is used when inserting the key object into the map and the equals
method is used when trying to retrieve a value from the map.
22. How does HashMap handle collisions in Java?
 The java.util.HashMap class in Java uses the approach of chaining to handle
collisions. In chaining, if the new values with the same key are attempted to be pushed,
then these values are stored in a linked list stored in a bucket of the key as a chain
along with the existing value.
 In the worst-case scenario, it can happen that all keys might have the same hashcode,
which will result in the hash table turning into a linked list. In this case, searching a
value will take O(n) complexity as opposed to O(1) time due to the nature of the linked
list. Hence, care has to be taken while selecting hashing algorithm.
23. What is the time complexity of basic operations get() and put() in
HashMap class?
The time complexity is O(1) assuming that the hash function used in the hash map
distributes elements uniformly among the buckets.

Data Structure Interview Questions for Experienced


24. What is binary tree data structure? What are the applications for
binary trees?
A binary tree is a data structure that is used to organize data in a way that allows for
efficient retrieval and manipulation. It is a data structure that uses two nodes, called
leaves and nodes, to represent the data. The leaves represent the data and the nodes
represent the relationships between the leaves. Each node has two children, called
siblings, and each child has one parent. The parent is the node that is closest to the
root of the tree. When a node is deleted from the tree, it is deleted from both its child
and its parent.
Following are some applications for binary tree data structure:
 It's widely used in computer networks for storing routing table information.
 Decision Trees.
 Expression Evaluation.
 Database indices.
25. What is binary search tree data structure? What are the applications
for binary search trees?
A binary search tree is a data structure that stores items in sorted order. In a binary
search tree, each node stores a key and a value. The key is used to access the item and
the value is used to determine whether the item is present or not. The key can be any
type of value such as an integer, floating point number, character string, or even a
combination of these types. The value can be any type of items such as an integer,
floating point number, character string, or even a combination of these types. When a
node is added to the tree, its key is used to access the item stored at that node. When
a node is removed from the tree, its key is used to access the item stored at that node.
A binary search tree is a special type of binary tree that has a specific order of
elements in it. It has three basic qualities:
 All elements in the left subtree of a node should have a value less than or equal to the
parent node's value, and
 All elements in the right subtree of a node should have a value greater than or equal to
the parent node's value.
 Both the left and right subtrees must be binary search trees too.
Following are some applications for binary tree data structure:
 It is used for indexing and multi-level indexing.
 It is used for implementing various search algorithms.
 It is helpful in organizing a sorted stream of data.
26. What are tree traversals?
Tree traversal is the process of visiting all the nodes of a tree. Since the root (head) is
the first node and all nodes are connected via edges (or links) we always start with that
node. There are three ways which we use to traverse a tree −
1. Inorder Traversal:
 Algorithm:
o Step 1. Traverse the left subtree, i.e., call Inorder(root.left)
o Step 2. Visit the root.
o Step 3. Traverse the right subtree, i.e., call Inorder(root.right)
 Inorder traversal in Java:
// Print inorder traversal of given tree.
void printInorderTraversal(Node root)
{
if (root == null)
return;
//first traverse to the left subtree
printInorderTraversal(root.left);
//then print the data of node
System.out.print(root.data + " ");
//then traverse to the right subtree
printInorderTraversal(root.right);
}
 Uses: In binary search trees (BST), inorder traversal gives nodes in ascending order.
2. Preorder Traversal:
 Algorithm:
o Step 1. Visit the root.
o Step 2. Traverse the left subtree, i.e., call Preorder(root.left)
o Step 3. Traverse the right subtree, i.e., call Preorder(root.right)
 Preorder traversal in Java:
// Print preorder traversal of given tree.
void printPreorderTraversal(Node root)
{
if (root == null)
return;
//first print the data of node
System.out.print(root.data + " ");
//then traverse to the left subtree
printPreorderTraversal(root.left);
//then traverse to the right subtree
printPreorderTraversal(root.right);
}
 Uses:
o Preorder traversal is commonly used to create a copy of the tree.
o It is also used to get prefix expression of an expression tree.
3. Postorder Traversal:
 Algorithm:
o Step 1. Traverse the left subtree, i.e., call Postorder(root.left)
o Step 2. Traverse the right subtree, i.e., call Postorder(root.right)
o Step 3. Visit the root.
 Postorder traversal in Java:
// Print postorder traversal of given tree.
void printPostorderTraversal(Node root)
{
if (root == null)
return;
//first traverse to the left subtree
printPostorderTraversal(root.left);
//then traverse to the right subtree
printPostorderTraversal(root.right);
//then print the data of node
System.out.print(root.data + " ");
}
 Uses:
o Postorder traversal is commonly used to delete the tree.
o It is also useful to get the postfix expression of an expression tree.
Consider the following tree as an example, then:
 Inorder Traversal => Left, Root, Right : [4, 2, 5, 1, 3]
 Preorder Traversal => Root, Left, Right : [1, 2, 4, 5, 3]
 Postorder Traversal => Left, Right, Root : [4, 5, 2, 3, 1]

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

Linked List O(1) O(n) O(1)

Binary Heap O(1) O(log n) O(log n)

Binary Search Tree O(1) O(log n) O(log n)

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”

BFS (Breadth First Search) finds the


DFS (Depth First Search) finds the shortest path using
shortest path using the Queue data
the Stack data structure.
structure.

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.

BFS necessitates more memory. DFS necessitates less memory.

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.

The DFS algorithm is a recursive algorithm that


Backtracking is not an option in BFS.
employs the concept of backtracking.

It is based on the FIFO principle (First In


It is based on the LIFO principle (Last In First Out).
First Out).

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

Following are some real-time applications for Trie data structure:


 Auto-Complete and Search for Search Engines
 Genome Analysis
 Data Analytics
 Browser History
 Spell Checker
37. Define Red-Black Tree and its applications
Red Black Trees are a type of self-balancing binary search tree. Rudolf Bayer invented
it in 1972 and dubbed it "symmetric binary B-trees."
A red-black tree is a Binary tree in which each node has a colour attribute, either red or
black. By comparing the node colours on any simple path from the root to a leaf, red-
black trees ensure that no path is more than twice as long as any other, ensuring that
the tree is generally balanced.
Red-black trees are similar to binary trees in that they both store their data in two's
complementary binary formats. However, red-black trees have one important
advantage over binary trees: they are faster to access. Because red-black trees are so
fast to access, they are often used to store large amounts of data.
Red-black trees can be used to store any type of data that can be represented as a set
of values.
Every Red-Black Tree Obeys the Following Rules:
 Every node is either red or black.
 The tree's root is always black.
 There are no two red nodes that are adjacent.
 There is the same number of black nodes on every path from a node to any of its
descendant's NULL nodes.
 All of the leaf nodes are black.
Following are some real-time applications for the Red-Black Tree data structure:
 The majority of self-balancing BST library functions in C++ or Java use Red-Black Trees.
 It is used to implement Linux CPU Scheduling.
 It is also used to reduce time complexity in the K-mean clustering algorithm in machine
learning.
 MySQL also employs the Red-Black tree for table indexes in order to reduce searching
and insertion time.
38. Which data structures are used for implementing LRU cache?
LRU cache or Least Recently Used cache allows quick identification of an element that
hasn’t been put to use for the longest time by organizing items in order of use. In
order to achieve this, two data structures are used:
 Queue – This is implemented using a doubly-linked list. The maximum size of the
queue is determined by the cache size, i.e by the total number of available frames. The
least recently used pages will be near the front end of the queue whereas the most
recently used pages will be towards the rear end of the queue.
 Hashmap – Hashmap stores the page number as the key along with the address of the
corresponding queue node as the value.
39. What is a heap data structure?
Heap is a special tree-based non-linear data structure in which the tree is a complete
binary tree. A binary tree is said to be complete if all levels are completely filled except
possibly the last level and the last level has all elements as left as possible. Heaps are
of two types:
 Max-Heap:
o In a Max-Heap the data element present at the root node must be the greatest
among all the data elements present in the tree.
o This property should be recursively true for all sub-trees of that binary tree.
 Min-Heap:
o In a Min-Heap the data element present at the root node must be the smallest
(or minimum) among all the data elements present in the tree.
o This property should be recursively true for all sub-trees of that binary tree.

Data Structure Coding Interview Questions


40. Write a program to remove duplicates from a sorted array in place?
 Input: {1, 1, 1, 2, 3, 3, 6, 6, 7}
 Output: {1, 2, 3, 6, 7}
 Explanation: The given input has only 1,2,3,6, and 7 as unique elements, hence the
output only lists them out.
#include <bits/stdc++.h>
using namespace std;

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++) {

if(a[i]!=a[index]) { //change index


index++; //swap next line
a[index]=a[i];
}
}
return index+1;
}
};

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

//Function to store the zigzag order traversal of a tree in a list.


vector <int> zigZagTraversal(Node* root)
{
//creating two stacks for level traversals in both order
stack<Node*> st1;
stack<Node*> st2;
//vector to store the zigzag traversal
vector<int> result;

//Initialize the first stack with the root element


st1.push(root);

//Iterate until either of the stack is not empty


while(!st1.empty() || !st2.empty()){
//iterate until the first stack is not empty
while(!st1.empty()){
Node* temp=st1.top();
st1.pop();
result.push_back(temp->data);

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;

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


char c = s[i];

// If the scanned character is


// an operand, add it to the output string.
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9'))
result += c;

// If the scanned character is an


// '(', push it to the stack.
else if (c == '(')
st.push('(');

// If the scanned character is an ')',


// pop and to output string from the stack
// until an '(' is encountered.
else if (c == ')') {
while (st.top() != '(') {
result += st.top();
st.pop();
}
st.pop();
}

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

// Pop all the remaining elements from the stack


while (!st.empty()) {
result += st.top();
st.pop();
}

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;

for(int i=0; i<row; i++) {


vector<int> v1;
for(int j=0; j<col; j++) {
v1.push_back(M[i][j]);
}
if(st.count(v1) == 0) {
v.push_back(v1);
st.insert(v1);
}
}

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;

}
};

void _quickSort(struct Node* l, struct Node *h)


{
if (h != NULL && l != h && l != h->next)
{
Solution ob;
struct Node *p = ob.partition(l, h);
_quickSort(l, p->prev);
_quickSort(p->next, h);
}
}

void quickSort(struct Node *head)


{
struct Node *h = lastNode(head);
_quickSort(head, h);
}
 Time Complexity: O(n^2) in the worst case when the list is already sorted. O(nlog(n))
in the best and average case.
 Space Complexity: O(n)
51. Write a function to connect nodes at the same level of a binary tree
Input: 100
/ \
13 15
/ \ \
14 1 20

Output: 100-> NULL


/ \
13 -> 15 -> NULL
/ \ \
14 -> 1 -> 20 -> NULL
class Solution
{
public:
//Function to connect nodes at the same level.
void connect(Node *p)
{
map<int,vector<Node *> > m;
queue<Node *> q;
queue<int> l;
q.push(p);
l.push(0);
while(!q.empty())
{
Node *temp=q.front();
int level=l.front();
q.pop();
l.pop();
m[level].push_back(temp);
if(temp->left!=NULL)
{
q.push(temp->left);
l.push(level+1);
}
if(temp->right!=NULL)
{
q.push(temp->right);
l.push(level+1);
}
}
for(map<int,vector<Node *> > ::iterator it=m.begin();it!=m.end();it+
+)
{
vector<Node *> temp1=it->second;
for(int i=0;i<temp1.size()-1;i++)
{
temp1[i]->nextRight=temp1[i+1];
}
temp1[temp1.size()-1]->nextRight=NULL;
}
}
};
 Time Complexity: O(n)
 Space Complexity: O(n)
52. Write a function to find number of structurally unique binary trees
are possible
Input: N = 3
Output: 5 for N = 3, there are 5 possible BSTs:
1 3 3 21
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
class Solution
{
public:
//function to calculate binomial coefficient C(n,k)
long long int binomialCoefficient(long long int n, long long int k)
{
long long int res = 1;
if (k > n - k)
k = n - k;

for (long long int i = 0; i < k; ++i)


{
res *= (n - i);
res /= (i + 1);
}
return res;
}

//function to calculate Nth Catalan Number


long long int catalanNumber(long long in n)
{
// Calculate value of 2nCn
long long int C = binomialCoefficient(2*n, n);

// return 2nCn/(n+1)
return C/(n+1);
}

//Function to return the total number of possible unique BST.


long long int numOfUniqueBinarySearchTrees(int n)
{
// find nth catalan number
long long int countOfUniqueBinarySearchTrees = catalanNumber(n);

// return nth catalan number


return countOfUniqueBinarySearchTrees;
}
};
 Time Complexity: O(n)
 Space Complexity: O(1)
53. Implement LRU(Least Recently Used) Cache
class LRUCache
{
private:
class node_t {
public:
int key;
int value;
node_t * next;
node_t * prev;
};

int cap;
node_t head;
unordered_map<int, node_t*> tbl;

void remove_node(node_t * node) {


node->next->prev = node->prev;
node->prev->next = node->next;
}
void add_node(node_t * node) {
node->next = head.next;
node->prev = &head;
head.next = node;
node->next->prev = node;
}
public:
//Constructor for initializing the cache capacity with the given value.
LRUCache(int cap): cap(cap)
{
// code here
head.prev = &head;
head.next = &head;
}

//Function to return value corresponding to the key.


int get(int key)
{
// your code here
unordered_map<int, node_t*>::iterator it = tbl.find(key);
if(it==tbl.end())
return -1;
remove_node(it->second);
add_node(it->second);
return it->second->value;
}

//Function for storing key-value pair.


void set(int key, int value)
{
// your code here
unordered_map<int, node_t*>::iterator it = tbl.find(key);
if(it!=tbl.end())
{
remove_node(it->second);
add_node(it->second);
it->second->value = value;
}
else {
node_t * node = new node_t;
node->key = key;
node->value = value;
add_node(node);
tbl[key] = node;
if(tbl.size()>cap) {
auto * old_node = head.prev;
tbl.erase(old_node->key);
remove_node(old_node);
delete old_node;
}
}
}
};
 Time Complexity: O(1) to get an element
 Space Complexity: O(n)
54. Write a function to determine whether duplicate elements in a given
array are within a given distance of each other.
 Input: arr[] = {1, 2, 3, 4, 2, 1, 2} range=3
 Output: True
class Solution {
public:

bool checkDuplicatesWithinRange(vector<int> arr, int range)


{
// Creating an empty hashset
unordered_set<int> myset;

// Traversing the input array


for (int i = 0; i < arr.size(); i++)
{
// If already present in hashset, then we found a duplicate
within range distance
if (myset.find(arr[i]) != myset.end())
return true;

// Add this item to hashset


myset.insert(arr[i]);

// Remove the range+1 distant item from the hashset


if (i >= range)
myset.erase(arr[i-range]);
}
return false;
}
};
 Time Complexity: O(n)
 Space Complexity: O(n)
55. Write a recursive function to calculate the height of a binary tree in
Java.
 Consider that every node of a tree represents a class called Node as given below:
public class Node{
int data;
Node left;
Node right;
}
 Then the height of the binary tree can be found as follows:
int heightOfBinaryTree(Node node)
{
if (node == null)
return 0; // If node is null then height is 0 for that node.
else
{
// compute the height of each subtree
int leftHeight = heightOfBinaryTree(node.left);
int rightHeight = heightOfBinaryTree(node.right);
//use the larger among the left and right height and plus 1
(for the root)
return Math.max(leftHeight, rightHeight) + 1;
}
}

56. Write Java code to count number of nodes in a binary tree


int countNodes(Node root)
{
int count = 1; //Root itself should be counted
if (root ==null)
return 0;
else
{
count += countNodes(root.left);
count += countNodes(root.right);
return count;
}
}

57. Print Left view of any binary trees.


 The main idea to solve this problem is to traverse the tree in pre order manner and
pass the level information along with it. If the level is visited for the first time, then we
store the information of the current node and the current level in the hashmap.
Basically, we are getting the left view by noting the first node of every level.
 At the end of traversal, we can get the solution by just traversing the map.
 Consider the following tree as example for finding the left view:
 Left view of a binary tree in Java:
import java.util.HashMap;

//to store a Binary Tree node


class Node
{
int data;
Node left = null, right = null;

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

// if you are visiting the level for the first time


// insert the current node and level info to the map
if (!map.containsKey(level)) {
map.put(level, root.data);
}

leftViewUtil(root.left, level + 1, map);


leftViewUtil(root.right, level + 1, map);
}

// to print left view of binary tree


public static void leftView(Node root)
{
// create an empty HashMap to store first node of each level
HashMap<Integer, Integer> map = new HashMap<>();
// traverse the tree and find out the first nodes of each level
leftViewUtil(root, 1, map);

// iterate through the HashMap and print the left view


for (int i = 0; i <map.size(); i++) {
System.out.print(map.get(i) + " ");
}
}

public static void main(String[] args)


{
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(6);
root.left.left = new Node(1);
root.left.left = new Node(3);
root.right.left = new Node(5);
root.right.right = new Node(7);
root.right.left.left = new Node(9);

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

public void mergeIslands(char[][] grid, int i, int j){


int m=grid.length;
int n=grid[0].length;

if(i<0||i>=m||j<0||j>=n||grid[i][j]!='1')
return;

grid[i][j]='X';

mergeIslands(grid, i-1, j);


mergeIslands(grid, i+1, j);
mergeIslands(grid, i, j-1);
mergeIslands(grid, i, j+1);
}
}

59. What is topological sorting in a graph?


 Topological sorting is a linear ordering of vertices such that for every directed edge ij,
vertex i comes before j in the ordering.
 Topological sorting is only possible for Directed Acyclic Graph (DAG).
 Applications:
1. jobs scheduling from the given dependencies among jobs.
2. ordering of formula cell evaluation in spreadsheets
3. ordering of compilation tasks to be performed in make files,
4. data serialization
5. resolving symbol dependencies in linkers.
 Topological Sort Code in Java:
// V - total vertices
// visited - boolean array to keep track of visited nodes
// graph - adjacency list.
// Main Topological Sort Function.
void topologicalSort()
{
Stack<Integer> stack = new Stack<Integer>();

// Mark all the vertices as not visited


boolean visited[] = new boolean[V];
for (int j = 0; j < V; j++){
visited[j] = false;
}
// Call the util function starting from all vertices one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack);

// Print contents of stack -> result of topological sort


while (stack.empty() == false)
System.out.print(stack.pop() + " ");
}

// A helper function used by topologicalSort


void topologicalSortUtil(int v, boolean visited[],
Stack<Integer> stack)
{
// Mark the current node as visited.
visited[v] = true;
Integer i;

// Recur for all the vertices adjacent to the current vertex


Iterator<Integer> it = graph.get(v).iterator();
while (it.hasNext()) {
i = it.next();
if (!visited[i])
topologicalSortUtil(i, visited, stack);
}

// Push current vertex to stack that saves result


stack.push(new Integer(v));
}

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/

SQL Interview Questions


1. What is Database?
A database is an organized collection of data, stored and retrieved digitally from a
remote or local computer system. Databases can be vast and complex, and such
databases are developed using fixed design and modeling approaches.
2. What is DBMS?
DBMS stands for Database Management System. DBMS is a system software
responsible for the creation, retrieval, updation, and management of the database. It
ensures that our data is consistent, organized, and is easily accessible by serving as an
interface between the database and its end-users or application software.
3. What is RDBMS? How is it different from DBMS?
RDBMS stands for Relational Database Management System. The key difference here,
compared to DBMS, is that RDBMS stores data in the form of a collection of tables,
and relations can be defined between the common fields of these tables. Most modern
database management systems like MySQL, Microsoft SQL Server, Oracle, IBM DB2,
and Amazon Redshift are based on RDBMS.
You can download a PDF version of Sql Interview Questions.

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

CREATE TABLE Students ( /* Create table with multiple fields as primary


key */
ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL,
CONSTRAINT PK_Student
PRIMARY KEY (ID, FirstName)
);

ALTER TABLE Students /* Set a column as primary key */


ADD PRIMARY KEY (ID);
ALTER TABLE Students /* Set multiple columns as primary key */
ADD CONSTRAINT PK_Student /*Naming a Primary Key*/
PRIMARY KEY (ID, FirstName);
write a sql statement to add primary key 't_id' to the table 'teachers'.

Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields
'col_b, col_c'.

9. What is a UNIQUE constraint?


A UNIQUE constraint ensures that all values in a column are different. This provides
uniqueness for the column(s) and helps identify each row uniquely. Unlike primary key,
there can be multiple unique constraints defined per table. The code syntax for
UNIQUE is quite similar to that of PRIMARY KEY and can be used interchangeably.
CREATE TABLE Students ( /* Create table with a single field as unique */
ID INT NOT NULL UNIQUE
Name VARCHAR(255)
);

CREATE TABLE Students ( /* Create table with multiple fields as unique */


ID INT NOT NULL
LastName VARCHAR(255)
FirstName VARCHAR(255) NOT NULL
CONSTRAINT PK_Student
UNIQUE (ID, FirstName)
);

ALTER TABLE Students /* Set a column as unique */


ADD UNIQUE (ID);
ALTER TABLE Students /* Set multiple columns as unique */
ADD CONSTRAINT PK_Student /* Naming a unique constraint */
UNIQUE (ID, FirstName);

10. What is a Foreign Key?


A FOREIGN KEY comprises of single or collection of fields in a table that essentially
refers to the PRIMARY KEY in another table. Foreign key constraint ensures referential
integrity in the relation between two tables.
The table with the foreign key constraint is labeled as the child table, and the table
containing the candidate key is labeled as the referenced or parent table.
CREATE TABLE Students ( /* Create table with foreign key - Way 1 */
ID INT NOT NULL
Name VARCHAR(255)
LibraryID INT
PRIMARY KEY (ID)
FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);

CREATE TABLE Students ( /* Create table with foreign key - Way 2 */


ID INT NOT NULL PRIMARY KEY
Name VARCHAR(255)
LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);

ALTER TABLE Students /* Add a new foreign key */


ADD FOREIGN KEY (LibraryID)
REFERENCES Library (LibraryID);
What type of integrity constraint does the foreign key ensure?

Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that references 'col_pk'
in 'table_x'.

11. What is a Join? List its different types.


The SQL Join clause is used to combine records (rows) from two or more tables in a
SQL database based on a related column between the two.
There are four different types of JOINs in SQL:
 (INNER) JOIN: Retrieves records that have matching values in both tables involved in
the join. This is the widely used join for queries.
SELECT *
FROM Table_A
JOIN Table_B;
SELECT *
FROM Table_A
INNER JOIN Table_B;
 LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched
records/rows from the right table.
SELECT *
FROM Table_A A
LEFT JOIN Table_B B
ON A.col = B.col;
 RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched
records/rows from the left table.
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
 FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left
or right table.
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;

Practice Problems
Solve these problems to ace this concept

Engineers Joined

Easy

20.2 Mins

Solve

Job Offer

Hard

22.30 Mins

Solve

12. What is a Self-Join?


A self JOIN is a case of regular join where a table is joined to itself based on some
relation between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN clause
and a table alias is used to assign different names to the table within the query.
SELECT A.emp_id AS "Emp_ID",A.emp_name AS "Employee",
B.emp_id AS "Sup_ID",B.emp_name AS "Supervisor"
FROM employee A, employee B
WHERE A.emp_sup = B.emp_id;
13. What is a Cross-Join?
Cross join can be defined as a cartesian product of the two tables included in the join.
The table after join contains the same number of rows as in the cross-product of the
number of rows in the two tables. If a WHERE clause is used in cross join then the
query will work like an INNER JOIN.
SELECT stu.name, sub.subject
FROM students AS stu
CROSS JOIN subjects AS sub;

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.

14. What is an Index? Explain its different types.


A database index is a data structure that provides a quick lookup of data in a column
or columns of a table. It enhances the speed of operations accessing data from a
database table at the cost of additional writes and memory to maintain the index data
structure.
CREATE INDEX index_name /* Create Index */
ON table_name (column_1, column_2);
DROP INDEX index_name; /* Drop Index */
There are different types of indexes that can be created for different purposes:
 Unique and Non-Unique Index:
Unique indexes are indexes that help maintain data integrity by ensuring that no two
rows of data in a table have identical key values. Once a unique index has been
defined for a table, uniqueness is enforced whenever keys are added or changed
within the index.
CREATE UNIQUE INDEX myIndex
ON students (enroll_no);
Non-unique indexes, on the other hand, are not used to enforce constraints on the
tables with which they are associated. Instead, non-unique indexes are used solely to
improve query performance by maintaining a sorted order of data values that are used
frequently.
 Clustered and Non-Clustered Index:
Clustered indexes are indexes whose order of the rows in the database corresponds to
the order of the rows in the index. This is why only one clustered index can exist in a
given table, whereas, multiple non-clustered indexes can exist in the table.
The only difference between clustered and non-clustered indexes is that the database
manager attempts to keep the data in the database in the same order as the
corresponding keys appear in the clustered index.
Clustering indexes can improve the performance of most query operations because
they provide a linear-access path to data stored in the database.
Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for fields
"column_1" & "column_2".

15. What is the difference between Clustered and Non-clustered index?


As explained above, the differences can be broken down into three small factors -
 Clustered index modifies the way records are stored in a database based on the
indexed column. A non-clustered index creates a separate entity within the table which
references the original table.
 Clustered index is used for easy and speedy retrieval of data from the database,
whereas, fetching records from the non-clustered index is relatively slower.
 In SQL, a table can have a single clustered index whereas it can have multiple non-
clustered indexes.
16. What is Data Integrity?
Data Integrity is the assurance of accuracy and consistency of data over its entire life-
cycle and is a critical aspect of the design, implementation, and usage of any system
which stores, processes, or retrieves data. It also defines integrity constraints to
enforce business rules on the data when it is entered into an application or a database.
17. What is a Query?
A query is a request for data or information from a database table or combination of
tables. A database query can be either a select query or an action query.
SELECT fname, lname /* select query */
FROM myDb.students
WHERE student_id = 1;
UPDATE myDB.students /* action query */
SET fname = 'Captain', lname = 'America'
WHERE student_id = 1;

18. What is a Subquery? What are its types?


A subquery is a query within another query, also known as a nested query or inner
query. It is used to restrict or enhance the data to be queried by the main query, thus
restricting or enhancing the output of the main query respectively. For example, here
we fetch the contact information for students who have enrolled for the maths subject:
SELECT name, email, mob, address
FROM myDb.contacts
WHERE roll_no IN (
SELECT roll_no
FROM myDb.students
WHERE subject = 'Maths');
There are two types of subquery - Correlated and Non-Correlated.
 A correlated subquery cannot be considered as an independent query, but it can refer
to the column in a table listed in the FROM of the main query.
 A non-correlated subquery can be considered as an independent query and the
output of the subquery is substituted in the main query.
Write a SQL query to update the field "status" in table "applications" from 0 to 1.

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

Job Offers 2.0

Hard

18.8 Mins

Solve

19. What is the SELECT statement?


SELECT operator in SQL is used to select data from a database. The data returned is
stored in a result table, called the result-set.
SELECT * FROM myDB.students;

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;

21. What are UNION, MINUS and INTERSECT commands?


The UNION operator combines and returns the result-set retrieved by two or more
SELECT statements.
The MINUS operator in SQL is used to remove duplicates from the result-set obtained
by the second SELECT query from the result-set obtained by the first SELECT query and
then return the filtered results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT
statements where records from one match the other and then returns this intersection
of result-sets.
Certain conditions need to be met before executing either of the above statements in
SQL -
 Each SELECT statement within the clause must have the same number of columns
 The columns must also have similar data types
 The columns in each SELECT statement should necessarily have the same order
SELECT name FROM Students /* Fetch the union of queries */
UNION
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch the union of queries with duplicates*/
UNION ALL
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
MINUS /* that aren't present in contacts */
SELECT name FROM Contacts;
SELECT name FROM Students /* Fetch names from students */
INTERSECT /* that are present in contacts as well */
SELECT name FROM Contacts;
Write a SQL query to fetch "names" that are present in either table "accounts" or in
table "registry".

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

22. What is Cursor? How to use a Cursor?


A database cursor is a control structure that allows for the traversal of records in a
database. Cursors, in addition, facilitates processing after traversal, such as retrieval,
addition, and deletion of database records. They can be viewed as a pointer to one
row in a set of rows.
Working with SQL Cursor:
1. DECLARE a cursor after any variable declaration. The cursor declaration must always be
associated with a SELECT Statement.
2. Open cursor to initialize the result set. The OPEN statement must be called before
fetching rows from the result set.
3. FETCH statement to retrieve and move to the next row in the result set.
4. Call the CLOSE statement to deactivate the cursor.
5. Finally use the DEALLOCATE statement to delete the cursor definition and release the
associated resources.
DECLARE @name VARCHAR(50) /* Declare All Required Variables */
DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/
SELECT name
FROM myDB.students
WHERE parent_name IN ('Sara', 'Ansh')
OPEN db_cursor /* Open cursor and Fetch data into @name */
FETCH next
FROM db_cursor
INTO @name
CLOSE db_cursor /* Close the cursor and deallocate the resources */
DEALLOCATE db_cursor

23. What are Entities and Relationships?


Entity: An entity can be a real-world object, either tangible or intangible, that can be
easily identifiable. For example, in a college database, students, professors, workers,
departments, and projects can be referred to as entities. Each entity has some
associated properties that provide it an identity.
Relationships: Relations or links between entities that have something to do with each
other. For example - The employee's table in a company's database can be associated
with the salary table in the same database.
24. List the different types of relationships in SQL.
 One-to-One - This can be defined as the relationship between two tables where each
record in one table is associated with the maximum of one record in the other table.
 One-to-Many & Many-to-One - This is the most commonly used relationship where a
record in a table is associated with multiple records in the other table.
 Many-to-Many - This is used in cases when multiple instances on both sides are
needed for defining a relationship.
 Self-Referencing Relationships - This is used when a table needs to define a
relationship with itself.
25. What is an Alias in SQL?
An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a
temporary name assigned to the table or table column for the purpose of a particular
SQL query. In addition, aliasing can be employed as an obfuscation technique to
secure the real names of database fields. A table alias is also called a correlation name.
An alias is represented explicitly by the AS keyword but in some cases, the same can
be performed without it as well. Nevertheless, using the AS keyword is always a good
practice.
SELECT A.emp_name AS "Employee" /* Alias using AS keyword */
B.emp_name AS "Supervisor"
FROM employee A, employee B /* Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;
Write an SQL statement to select all from table "Limited" with alias "Ltd".

26. What is a View?


A view in SQL is a virtual table based on the result-set of an SQL statement. A view
contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.
27. What is Normalization?
Normalization represents the way of organizing structured data in the database
efficiently. It includes the creation of tables, establishing relationships between them,
and defining rules for those relationships. Inconsistency and redundancy can be kept
in check based on these rules, hence, adding flexibility to the database.
28. What is Denormalization?
Denormalization is the inverse process of normalization, where the normalized schema
is converted into a schema that has redundant information. The performance is
improved by using redundancy and keeping the redundant data consistent. The reason
for performing denormalization is the overheads produced in the query processor by
an over-normalized structure.
29. What are the various forms of Normalization?
Normal Forms are used to eliminate or reduce redundancy in database tables. The
different forms are as follows:
 First Normal Form:
A relation is in first normal form if every attribute in that relation is a single-valued
attribute. If a relation contains a composite or multi-valued attribute, it violates the
first normal form. Let's consider the following students table. Each student in the table,
has a name, his/her address, and the books they issued from the public library -
Students Table
Student Address Books Issued Salutation

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.

24th Street Park Beautiful Bad (Annie Ward), Woman 99 (Greer


Sara Mrs.
Avenue Macallister)

Ansh Windsor Street 777 Dracula (Bram Stoker) 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 Amanora Park Town 94 Inception (Christopher Nolan) Ms.

Ansh 62nd Sector A-10 The Alchemist (Paulo Coelho) Mr.

Ansh 62nd Sector A-10 Inferno (Dan Brown) Mr.

Sara 24th Street Park Avenue Beautiful Bad (Annie Ward) Mrs.

Sara 24th Street Park Avenue Woman 99 (Greer Macallister) Mrs.

Ansh Windsor Street 777 Dracula (Bram Stoker) Mr.

 Second Normal Form:


A relation is in second normal form if it satisfies the conditions for the first normal
form and does not contain any partial dependency. A relation in 2NF has no partial
dependency, i.e., it has no non-prime attribute that depends on any proper subset of
any candidate key of the table. Often, specifying a single column Primary Key is the
solution to the problem. Examples -
Example 1 - Consider the above example. As we can observe, the Students Table in
the 1NF form has a candidate key in the form of [Student, Address] that can uniquely
identify all records in the table. The field Books Issued (non-prime attribute) depends
partially on the Student field. Hence, the table is not in 2NF. To convert it into the 2nd
Normal Form, we will partition the tables into two while specifying a new Primary
Key attribute to identify the individual records in the Students table. The Foreign
Key constraint will be set on the other table to ensure referential integrity.
Students Table (2nd Normal Form)
Student_ID Student Address Salutation

1 Sara Amanora Park Town 94 Ms.

2 Ansh 62nd Sector A-10 Mr.

3 Sara 24th Street Park Avenue Mrs.

4 Ansh Windsor Street 777 Mr.

Books Table (2nd Normal Form)


Student_ID Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

Example 2 - Consider the following dependencies in relation to R(W,X,Y,Z)


WX -> Y [W and X together determine Y]
XY -> Z [X and Y together determine Z]
Here, WX is the only candidate key and there is no partial dependency, i.e., any proper
subset of WX doesn’t determine any non-prime attribute in the relation.
 Third Normal Form
A relation is said to be in the third normal form, if it satisfies the conditions for the
second normal form and there is no transitive dependency between the non-prime
attributes, i.e., all non-prime attributes are determined only by the candidate keys of
the relation and not by any other non-prime attribute.
Example 1 - Consider the Students Table in the above example. As we can observe,
the Students Table in the 2NF form has a single candidate key Student_ID (primary
key) that can uniquely identify all records in the table. The field Salutation (non-prime
attribute), however, depends on the Student Field rather than the candidate key.
Hence, the table is not in 3NF. To convert it into the 3rd Normal Form, we will once
again partition the tables into two while specifying a new Foreign Key constraint to
identify the salutations for individual records in the Students table. The Primary
Key constraint for the same will be set on the Salutations table to identify each record
uniquely.
Students Table (3rd Normal Form)
Student_ID Student Address Salutation_ID

1 Sara Amanora Park Town 94 1

2 Ansh 62nd Sector A-10 2

3 Sara 24th Street Park Avenue 3

4 Ansh Windsor Street 777 1

Books Table (3rd Normal Form)


Student_ID Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

Salutations Table (3rd Normal Form)


Salutation_ID Salutation

1 Ms.

2 Mr.

3 Mrs.

Example 2 - Consider the following dependencies in relation to R(P,Q,R,S,T)


P -> QR [P together determine C]
RS -> T [B and C together determine D]
Q -> S
T -> P
For the above relation to exist in 3NF, all possible candidate keys in the above relation
should be {P, RS, QR, T}.
 Boyce-Codd Normal Form
A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal
form and for every functional dependency, Left-Hand-Side is super key. In other
words, a relation in BCNF has non-trivial functional dependencies in form X –> Y, such
that X is always a super key. For example - In the above example, Student_ID serves as
the sole unique identifier for the Students Table and Salutation_ID for the Salutations
Table, thus these tables exist in BCNF. The same cannot be said for the Books Table
and there can be several books with common Book Names and the same Student_ID.
30. What are the TRUNCATE, DELETE and DROP statements?
DELETE statement is used to delete rows from a table.
DELETE FROM Candidates
WHERE CandidateId > 1000;
TRUNCATE command is used to delete all the rows from the table and free the space
containing the table.
TRUNCATE TABLE Candidates;
DROP command is used to remove an object from the database. If you drop a table,
all the rows in the table are deleted and the table structure is removed from the
database.
DROP TABLE Candidates;
Write a SQL statement to wipe a table 'Temporary' from memory.

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.

37. What is Collation? What are the different types of Collation


Sensitivity?
Collation refers to a set of rules that determine how data is sorted and compared.
Rules defining the correct character sequence are used to sort the character data. It
incorporates options for specifying case sensitivity, accent marks, kana character types,
and character width. Below are the different types of collation sensitivity:
 Case sensitivity: A and a are treated differently.
 Accent sensitivity: a and á are treated differently.
 Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated
differently.
 Width sensitivity: Same character represented in single-byte (half-width) and double-
byte (full-width) are treated differently.
38. What is a Stored Procedure?
A stored procedure is a subroutine available to applications that access a relational
database management system (RDBMS). Such procedures are stored in the database
data dictionary. The sole disadvantage of stored procedure is that it can be executed
nowhere except in the database and occupies more memory in the database server. It
also provides a sense of security and functionality as users who can't access the data
directly can be granted access via stored procedures.
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;

39. What is a Recursive Stored Procedure?


A stored procedure that calls itself until a boundary condition is reached, is called a
recursive stored procedure. This recursive function helps the programmers to deploy
the same set of code several times as and when required. Some SQL programming
languages limit the recursion depth to prevent an infinite loop of procedure calls from
causing a stack overflow, which slows down the system and may lead to system
crashes.
DELIMITER $$ /* Set a new delimiter => $$ */
CREATE PROCEDURE calctotal( /* Create the procedure */
IN number INT, /* Set Input and Ouput variables */
OUT total INT
) BEGIN
DECLARE score INT DEFAULT NULL; /* Set the default value => "score" */
SELECT awards FROM achievements /* Update "score" via SELECT query */
WHERE id = number INTO score;
IF score IS NULL THEN SET total = 0; /* Termination condition */
ELSE
CALL calctotal(number+1); /* Recursive call */
SET total = total + score; /* Action after recursion */
END IF;
END $$ /* End of procedure */
DELIMITER ; /* Reset the delimiter */

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;

41. What is Pattern Matching in SQL?


SQL pattern matching provides for pattern search in data if you have no clue as to
what that word should be. This kind of SQL query uses wildcards to match a string
pattern, rather than writing the exact word. The LIKE operator is used in conjunction
with SQL Wildcards to fetch the required information.
 Using the % wildcard to perform a simple search
The % wildcard matches zero or more characters of any type and can be used to
define wildcards both before and after the pattern. Search a student in your database
with first name beginning with the letter K:
SELECT *
FROM students
WHERE first_name LIKE 'K%'
 Omitting the patterns using the NOT keyword
Use the NOT keyword to select records that don't match the pattern. This query
returns all students whose first name does not begin with K.
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
 Matching a pattern anywhere using the % wildcard twice
Search for a student in the database where he/she has a K in his/her first name.
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
 Using the _ wildcard to match pattern at a specific position
The _ wildcard matches exactly one character of any type. It can be used in conjunction
with % wildcard. This query fetches all students with letter K at the third position in
their first name.
SELECT *
FROM students
WHERE first_name LIKE '__K%'
 Matching patterns for a specific length
The _ wildcard plays an important role as a limitation when it matches exactly one
character. It limits the length and position of the matched results. For example -
SELECT * /* Matches first names with three or more letters */
FROM students
WHERE first_name LIKE '___%'

SELECT * /* Matches first names with exactly four characters */


FROM students
WHERE first_name LIKE '____'

PostgreSQL Interview Questions


42. What is PostgreSQL?
PostgreSQL was first called Postgres and was developed by a team led by Computer
Science Professor Michael Stonebraker in 1986. It was developed to help developers
build enterprise-level applications by upholding data integrity by making systems
fault-tolerant. PostgreSQL is therefore an enterprise-level, flexible, robust, open-
source, and object-relational DBMS that supports flexible workloads along with
handling concurrent users. It has been consistently supported by the global developer
community. Due to its fault-tolerant nature, PostgreSQL has gained widespread
popularity among developers.
43. How do you define Indexes in PostgreSQL?
Indexes are the inbuilt functions in PostgreSQL which are used by the queries to
perform search more efficiently on a table in the database. Consider that you have a
table with thousands of records and you have the below query that only a few records
can satisfy the condition, then it will take a lot of time to search and return those rows
that abide by this condition as the engine has to perform the search operation on
every single to check this condition. This is undoubtedly inefficient for a system
dealing with huge data. Now if this system had an index on the column where we are
applying search, it can use an efficient method for identifying matching rows by
walking through only a few levels. This is called indexing.
Select * from some_table where table_col=120

44. How will you change the datatype of a column?


This can be done by using the ALTER TABLE statement as shown below:
Syntax:
ALTER TABLE tname
ALTER COLUMN col_name [SET DATA] TYPE new_data_type;

45. What is the command used for creating a database in PostgreSQL?


The first step of using PostgreSQL is to create a database. This is done by using the
createdb command as shown below: createdb db_name
After running the above command, if the database creation was successful, then the
below message is shown:
CREATE DATABASE

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

47. What are partitioned tables called in PostgreSQL?


Partitioned tables are logical structures that are used for dividing large tables into
smaller structures that are called partitions. This approach is used for effectively
increasing the query performance while dealing with large database tables. To create a
partition, a key called partition key which is usually a table column or an expression,
and a partitioning method needs to be defined. There are three types of inbuilt
partitioning methods provided by Postgres:
 Range Partitioning: This method is done by partitioning based on a range of values.
This method is most commonly used upon date fields to get monthly, weekly or yearly
data. In the case of corner cases like value belonging to the end of the range, for
example: if the range of partition 1 is 10-20 and the range of partition 2 is 20-30, and
the given value is 10, then 10 belongs to the second partition and not the first.
 List Partitioning: This method is used to partition based on a list of known values.
Most commonly used when we have a key with a categorical value. For example,
getting sales data based on regions divided as countries, cities, or states.
 Hash Partitioning: This method utilizes a hash function upon the partition key. This is
done when there are no specific requirements for data division and is used to access
data individually. For example, you want to access data based on a specific product,
then using hash partition would result in the dataset that we require.
The type of partition key and the type of method used for partitioning determines how
positive the performance and the level of manageability of the partitioned table are.
48. Define tokens in PostgreSQL?
A token in PostgreSQL is either a keyword, identifier, literal, constant, quotes identifier,
or any symbol that has a distinctive personality. They may or may not be separated
using a space, newline or a tab. If the tokens are keywords, they are usually commands
with useful meanings. Tokens are known as building blocks of any PostgreSQL code.
49. What is the importance of the TRUNCATE statement?
TRUNCATE TABLE name_of_table statement removes the data efficiently and quickly
from the table.
The truncate statement can also be used to reset values of the identity columns along
with data cleanup as shown below:
TRUNCATE TABLE name_of_table
RESTART IDENTITY;
We can also use the statement for removing data from multiple tables all at once by
mentioning the table names separated by comma as shown below:
TRUNCATE TABLE
table_1,
table_2,
table_3;

50. What is the capacity of a table in PostgreSQL?


The maximum size of PostgreSQL is 32TB.
51. Define sequence.
A sequence is a schema-bound, user-defined object which aids to generate a
sequence of integers. This is most commonly used to generate values to identity
columns in a table. We can create a sequence by using the CREATE
SEQUENCE statement as shown below:
CREATE SEQUENCE serial_num START 100;
To get the next number 101 from the sequence, we use the nextval() method as shown
below:
SELECT nextval('serial_num');
We can also use this sequence while inserting new records using the INSERT
command:
INSERT INTO ib_table_name VALUES (nextval('serial_num'), 'interviewbit');

52. What are string constants in PostgreSQL?


They are character sequences bound within single quotes. These are using during data
insertion or updation to characters in the database.
There are special string constants that are quoted in dollars.
Syntax: $tag$<string_constant>$tag$ The tag in the constant is optional and when we
are not specifying the tag, the constant is called a double-dollar string literal.
53. How can you get a list of all databases in PostgreSQL?
This can be done by using the command \l -> backslash followed by the lower-case
letter L.
54. How can you delete a database in PostgreSQL?
This can be done by using the DROP DATABASE command as shown in the syntax
below:
DROP DATABASE database_name;
If the database has been deleted successfully, then the following message would be
shown:
DROP DATABASE
55. What are ACID properties? Is PostgreSQL compliant with ACID?
ACID stands for Atomicity, Consistency, Isolation, Durability. They are database
transaction properties which are used for guaranteeing data validity in case of errors
and failures.
 Atomicity: This property ensures that the transaction is completed in all-or-nothing
way.
 Consistency: This ensures that updates made to the database is valid and follows rules
and restrictions.
 Isolation: This property ensures integrity of transaction that are visible to all other
transactions.
 Durability: This property ensures that the committed transactions are stored
permanently in the database.
PostgreSQL is compliant with ACID properties.
56. Can you explain the architecture of PostgreSQL?
 The architecture of PostgreSQL follows the client-server model.
 The server side comprises of background process manager, query processer, utilities
and shared memory space which work together to build PostgreSQL’s instance that has
access to the data. The client application does the task of connecting to this instance
and requests data processing to the services. The client can either be GUI (Graphical
User Interface) or a web application. The most commonly used client for PostgreSQL is
pgAdmin.
57. What do you understand by multi-version concurrency control?
MVCC or Multi-version concurrency control is used for avoiding unnecessary database
locks when 2 or more requests tries to access or modify the data at the same time.
This ensures that the time lag for a user to log in to the database is avoided. The
transactions are recorded when anyone tries to access the content.
For more information regarding this, you can refer here.
58. What do you understand by command enable-debug?
The command enable-debug is used for enabling the compilation of all libraries and
applications. When this is enabled, the system processes get hindered and generally
also increases the size of the binary file. Hence, it is not recommended to switch this
on in the production environment. This is most commonly used by developers to
debug the bugs in their scripts and help them spot the issues. For more information
regarding how to debug, you can refer here.
59. How do you check the rows affected as part of previous
transactions?
SQL standards state that the following three phenomena should be prevented whilst
concurrent transactions. SQL standards define 4 levels of transaction isolations to deal
with these phenomena.
 Dirty reads: If a transaction reads data that is written due to concurrent uncommitted
transaction, these reads are called dirty reads.
 Phantom reads: This occurs when two same queries when executed separately return
different rows. For example, if transaction A retrieves some set of rows matching search
criteria. Assume another transaction B retrieves new rows in addition to the rows
obtained earlier for the same search criteria. The results are different.
 Non-repeatable reads: This occurs when a transaction tries to read the same row
multiple times and gets different values each time due to concurrency. This happens
when another transaction updates that data and our current transaction fetches that
updated data, resulting in different values.
To tackle these, there are 4 standard isolation levels defined by SQL standards. They
are as follows:
 Read Uncommitted – The lowest level of the isolations. Here, the transactions are not
isolated and can read data that are not committed by other transactions resulting in
dirty reads.
 Read Committed – This level ensures that the data read is committed at any instant of
read time. Hence, dirty reads are avoided here. This level makes use of read/write lock
on the current rows which prevents read/write/update/delete of that row when the
current transaction is being operated on.
 Repeatable Read – The most restrictive level of isolation. This holds read and write
locks for all rows it operates on. Due to this, non-repeatable reads are avoided as other
transactions cannot read, write, update or delete the rows.
 Serializable – The highest of all isolation levels. This guarantees that the execution is
serializable where execution of any concurrent operations are guaranteed to be
appeared as executing serially.
The following table clearly explains which type of unwanted reads the levels avoid:
Isolation levels Dirty Reads Phantom Reads Non-repeatable reads

Read Uncommitted Might occur Might occur Might occur

Read Committed Won’t occur Might occur Might occur

Repeatable Read Won’t occur Might occur Won’t occur

Serializable Won’t occur Won’t occur Won’t occur

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.*'

63. How will you take backup of the database in PostgreSQL?


We can achieve this by using the pg_dump tool for dumping all object contents in the
database into a single file. The steps are as follows:
Step 1: Navigate to the bin folder of the PostgreSQL installation path.
C:\>cd C:\Program Files\PostgreSQL\10.0\bin
Step 2: Execute pg_dump program to take the dump of data to a .tar folder as shown
below:
pg_dump -U postgres -W -F t sample_data > C:\Users\admin\pgbackup\
sample_data.tar
The database dump will be stored in the sample_data.tar file on the location specified.
64. Does PostgreSQL support full text search?
Full-Text Search is the method of searching single or collection of documents stored
on a computer in a full-text based database. This is mostly supported in advanced
database systems like SOLR or ElasticSearch. However, the feature is present but is
pretty basic in PostgreSQL.
65. What are parallel queries in PostgreSQL?
Parallel Queries support is a feature provided in PostgreSQL for devising query plans
capable of exploiting multiple CPU processors to execute the queries faster.
66. Differentiate between commit and checkpoint.
The commit action ensures that the data consistency of the transaction is maintained
and it ends the current transaction in the section. Commit adds a new record in the log
that describes the COMMIT to the memory. Whereas, a checkpoint is used for writing
all changes that were committed to disk up to SCN which would be kept in datafile
headers and control files.
Conclusion:
SQL is a language for the database. It has a vast scope and robust capability of
creating and manipulating a variety of database objects using commands like CREATE,
ALTER, DROP, etc, and also in loading the database objects using commands like
INSERT. It also provides options for Data Manipulation using commands like DELETE,
TRUNCATE and also does effective retrieval of data using cursor commands like
FETCH, SELECT, etc. There are many such commands which provide a large amount of
control to the programmer to interact with the database in an efficient way without
wasting many resources. The popularity of SQL has grown so much that almost every
programmer relies on this to implement their application's storage functionalities
thereby making it an exciting language to learn. Learning this provides the developer a
benefit of understanding the data structures used for storing the organization's data
and giving an additional level of control and in-depth understanding of the
application.
PostgreSQL being an open-source database system having extremely robust and
sophisticated ACID, Indexing, and Transaction supports has found widespread
popularity among the developer community.
References and Resources:
 PostgreSQL Download
 PostgreSQL Tutorial
 SQL Guide
 SQL Server Interview Questions
 SQL Query Interview Questions and Answers
 SQL Interview Questions for Data Science
 MySQL Interview Questions
 DBMS Interview Questions
 PL SQL Interview Questions
 MongoDB Interview Questions
 Database Testing Interview Questions
 SQL Vs MySQL
 PostgreSQL vs MySQL
 Difference Between SQL and PLSQL
 SQL Vs NoSQL
 SQL IDE
 SQL Projects
 MySQL Commands
 SQL Books
SQL MCQ
1.

Which statement is true for a PRIMARY KEY constraint?


Primary key defines a realtionship between two tables.

A table in SQL must have a primary key associated with it to uniquely identify its records.

A table in SQL is indexed by default based on its primary key.

Primary key may or may not be unique but can be comprised of multiple fields.

2.

Which statement is false for a FOREIGN KEY constraint?


Foreign key defines a relationship between two tables.

Foreign Key is automatically created when two tables are joined.

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.

A request for data from a table in the database.

A request to input data from the user.

A request for data from single or multiple tables in the database.

4.

What does SQL stand for?


Structured Question Language

Strong Query Language

Structured Query Language

Strong Question Language

5.
Which statement is used to update data in the database?
MODIFY

UPDATE

ALTER TABLE

SAVE AS

6.

Query to select all records with "bar" in their name?


SELECT * FROM people WHERE name = "%bar%";

SELECT * FROM people WHERE name LIKE "%bar%";

SELECT * FROM people WHERE name IN ("bar");

SELECT * FROM people WHERE name = "_bar_"

7.

Which statement is false for the ORDER BY statement?


Requires a ASC or DESC keyword explicitly to sort the result set.

Sorts the result set in descending order using the DESC keyword.

Can sort based on multiple columns

None of the above.

8.

SQL query used to fetch unique values from a field?


SELECT UNIQUE column_name FROM table_name;

SELECT DISTINCT column_name FROM table_name;

SELECT column_name FROM table_name WHERE COUNT(column_name) = 1;

SELECT UNIQUE column_name FROM table_name WHERE COUNT(column_name) = 1;

9.

What is the main advantage of a clustered index over a non-clustered index?


It is easier to create and manipulate.

It requires extra memory but allows for speedy retrieval of records.


It does not require additional memory and allows for speedy retrieval of records.

None of the above.

10.

Normalization which has neither composite values nor partial dependencies?


Second Normal Formal

Third Normal Form

Boyce-Codd Normal Form

All of the above

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;

DROP FROM TABLE table_name;

DELETE FROM TABLE table_name;

TRUNCATE TABLE table_name;

12.

Which of the following is known as a virtual table in SQL?


SELF JOIN

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.

What statement is used for adding data to PostgreSQL?


UPDATE

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

Results are shown in ascending order

Results display is random

Results are shown in ascending and descending order alternately.

16.

Which command is used to tell PostgreSQL to make all changes made to the database
permanent?
Submit

Execute

Apply

Commit

17.

What is a pre-requisite for creating a database in PostgreSQL?To create a database in


PostgreSQL, you must have the special CREATEDB privilege or
Super user privilege or CREATEDB privilege

Admin privilege

CREATEDBL privilege and Super user privilege

Just run the script

18.
What command is used for restoring the backup of PostgreSQL which was created
using pg_dump?
psql -R db_dump.psql db_name

psql -r db_dump.psql db_name

psql -f db_dump.psql db_name

psql -F db_dump.psql db_name

19.

What allows us to define how various tables are related to each other formally in a
database?
Views

Foreign Key Constraints

Primary Key Constraints

Database manager

20.

SQL
What languages are supported by PostgreSQL?
PL/pgSQL, PL/Tcl, PL/Perl and PL/Python

PL/pgSQL, PL/Pcl, PL/Ruby and PL/Java

PL/Perl, PL/Dcl, PL/Dtl and PL/Dml

Only SQL

You might also like