0% found this document useful (0 votes)
20 views44 pages

PADA Role TECH Questions

The document provides a comprehensive overview of various programming concepts in Java, C, C++, and Python, including the use of the 'static' keyword, interface implementation, polymorphism, memory allocation, and data structures like arrays and ArrayLists. It also explains key differences between programming languages, the significance of lambda expressions, and concepts like normalization in databases and classifiers in machine learning. Additionally, it covers specific functions in C++ and Python, such as getch(), friend functions, and the map() function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views44 pages

PADA Role TECH Questions

The document provides a comprehensive overview of various programming concepts in Java, C, C++, and Python, including the use of the 'static' keyword, interface implementation, polymorphism, memory allocation, and data structures like arrays and ArrayLists. It also explains key differences between programming languages, the significance of lambda expressions, and concepts like normalization in databases and classifiers in machine learning. Additionally, it covers specific functions in C++ and Python, such as getch(), friend functions, and the map() function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

1. What is the use of “static” keyword in Java?

● The static keyword is a non-access modifier in Java that is useful for memory
management.
● Static property can be shared by all the objects, no separate copies of static
members will be created on object creation.
● No need to create the instance of the class for accessing static members, we can
directly access them by using the class name.
● The static keyword can be used with the variable, block, method, and nested
classes for memory management.
○ Static variable: When a variable is declared with the static keyword, a single
copy of the variable will be created and the same variable will be shared
across all objects of the class (a class to which the static variable belongs).
○ Static block: A static block helps with the initialization of the static data
members. It is a group of statements within a Java class and gets executed
exactly once when the class is first loaded into the JVM(Java Virtual
Machine).
○ Static method: If the method is declared with the static keyword, then it is
considered a static method. The main( ) method is one of the examples of a
static method. Static methods are having restrictions such as they can
directly call other static methods only, and they can access static data
directly.
○ Static class: Only a nested class can be created as a static class. Nested
static class doesn’t need a reference of Outer class(a class in which the
nested class is defined). A static class does not have permission to access
non-static members of the Outer class.
2. Can we implement multiple interfaces in a single Java class?
Yes, it is allowed to implement multiple interfaces in a single class. In Java, multiple
inheritances is achieved by implementing multiple interfaces into the class. While
implementing, each interface name is separated by using a comma(,) operator.
Syntax:
public class ClassName implements Interface1, Interface2,..., InterfaceN
{
//Code
}
Example:
public class InterviewBit implements X, Y
{
//Code
}
Here, X and Y are the interfaces implemented by the class InterviewBit.
3. What is the significance of the “super” and “this” keywords in Java?
● super keyword: In Java, the “super” keyword is used to provide reference to the
instance of the parent class(superclass). Since it is a reserved keyword in Java, it
cannot be used as an identifier. This keyword can also be used to invoke parent
class members like constructors and methods.
● this Keyword: In Java, the “this” keyword is used to refer to the instance of the
current class. Since it is a reserved keyword in Java, it cannot be used as an
identifier. It can be used for referring object of the current class, to invoke a
constructor of the current class, to pass as an argument in the method call or
constructor call, to return the object of the current class.
4. What is run-time polymorphism and how it is achieved in Java?
● Run-time polymorphism(dynamic binding or dynamic method dispatch) implies that
the call to an overridden method is resolved dynamically during run-time instead of
compile-time.
● Run-time polymorphism is achieved with the help of method overriding in Java.
When a child class(subclass) has the same method name, return type, and
parameters as the parent(superclass), then that method overrides the superclass
method, this process is known as method overriding.
Example:
The below example has one superclass Animal and three subclasses, Birds,
Mammals, and Reptiles. Subclasses extend the superclass and override its print()
method. We will call the print() method with the help of the reference variable of
Animal class i.e., parent class. The subclass method is invoked during runtime since
it is referring to the object of the subclass and the subclass method overrides the
superclass method. As Java Virtual Machine(JVM) decides method invocation, it is
run-time polymorphism.
class Animal{
void print(){
System.out.println("Inside Animal");
}
}
class Birds extends Animal{
void print(){
System.out.println("Inside Birds");
}
}
class Mammals extends Animal{
void print(){
System.out.println("Inside Mammals");
}
}
class Reptiles extends Animal{
void print(){
System.out.println("Inside Reptiles");
}
}
class InterviewBit{
public static void main(String args[]){
Animal a = new Animal();
Animal b = new Birds(); //upcasting
Animal m = new Mammals(); //upcasting
Animal r = new Reptiles(); //upcasting
a.print();
b.print();
m.print();
r.print();
}
}
Output:
Inside Animal
Inside Birds
Inside Mammals
Inside Reptiles
5. Distinguish between Array and ArrayList provided by Java.
Array ArrayList

An array is of fixed length ArrayList is of variable length

Length of the array cannot be changed Length of the array can be changed after
once created creation

It can store both primitive types and objects It can store only objects, not primitives(it
automatically converts primitive type to
object)

Using an assignment operator we can store With the help of add() method elements are
elements into an array stored into an ArrayList

An array can be multi-dimensional ArrayList is always one-dimensional

6. What is the “Diamond problem” in Java?


The “Diamond problem” usually happens in multiple inheritances. Java does not support
multiple inheritances, so in the case of Java, the diamond problem occurs when you are
trying to implement multiple interfaces. When two interfaces having methods with the same
signature are implemented to a single class, it creates ambiguity for the compiler about
which function it has to call, so it produces an error at the compile time. Its structure looks
similar to diamond thus it is called a “Diamond problem

Here, if we try to access the print() function using the DerivedClass3 object, it will create
confusion for the compiler that which copy of the print() function it has to call i.e., from
DerivedClass1 or DervivedClass2.
“Diamond problem” is solved by using virtual inheritance. It guarantees that the child class
will get only one instance of the common base class.
7. How can you differentiate between C, C++, and Java?

C C++ Java

It is a procedural language. It is an object-oriented It is an object-oriented


language (not purely object- language (not purely object-
oriented as it is possible to oriented, as it supports
write code without the primitive data types).
creation of a class).

It supports pointers. It supports pointers. It does not support pointers.

Platform dependent Platform dependent Platform independent


language language language

Not possible to create our It is allowed to create the Here, we can create our
own package. package in C++. package and can include
the classes.

The concept of inheritance We can use multiple It does not support multiple
was not implemented. inheritances in C++. inheritances.

It does not support data It supports data hiding, so It supports data hiding, so
hiding, so data is less data cannot be accessed by data cannot be accessed by
secured as it can be the outside world. the outside world.
accessed by the outside
world.

8. What are lambda expressions in Java?


● A Lambda expression is a function that can be created without including it in any
class. It was introduced in Java 8.
● It is used to provide the interface implementation which has a functional interface. It
does not require defining the method again for providing the implementation, it is
allowed to just write the implementation code. Thus it saves plenty of coding.
● Lambda expression is considered as a function, the .class file will not be created
by the compiler.
● They are generally used for simple callbacks or event listeners implementation, or in
functional programming with the Java Streams API.
● Lambda Expression Syntax is:
(argument_list) -> {body}
Three components of Lamda expression are:
1. argument_list: Zero or more number of arguments.
2. -> (arrow-token): Used to link argument_list and body of lambda expression.
3. body: Contains statements and expressions for lambda expression.
● A Java example program to illustrate lambda expressions by implementing the user-
defined functional interface is given below:
// A functional interface with a single abstract method.
interface ExampleInterface
{
// An abstract method
void abstractPrint(int a);
}
class InterviewBit
{
public static void main(String args[])
{
/* A lambda expression to implement the above functional interface. */
ExampleInterface ob = (int a)->{System.out.println(a)};

// This calls above lambda expression and prints 20.


ob.abstractPrint(20);
}
}
In the above example program, Example Interface is the functional interface that has a
single abstract method abstractPrint(). By using lambda expression within InterviewBit
class, we are implementing the functional interface by providing implementation code for the
abstract method within an interface.
9. Can you differentiate between “var++” and “++var”?
Expressions “var++” and “++var” are used for incrementing the value of the “var” variable.
“var++” will first give the evaluation of expression and then its value will be incremented by
1, thus it is called as post-incrementation of a variable. “++var” will increment the value of
the variable by one and then the evaluation of the expression will take place, thus it is called
pre-incrementation of a variable.
Example:
/* C program to demonstrate the difference between var++ and ++var */

#include<stdio.h>
int main()
{
int x,y;
x=7, y=1;
printf("%d %d\n", x++, x); //will generate 7, 8 as output
printf("%d %d", ++y, y); //will generate 2, 2 as output
}
10. Explain memory allocation process in C.
● Memory allocation process indicates reserving some part of the memory space
based on the requirement for the code execution.
● There are two types of memory allocation done in C:
1. Static memory allocation: The memory allocation during the beginning of the
program is known as static memory allocation. In this type of memory
allocation allocated memory size remains fixed and it is not allowed to
change the memory size during run-time. It will make use of a stack for
memory management.
2. Dynamic memory allocation: The memory allocation during run-time is
considered as dynamic memory allocation. We can mention the size at
runtime as per requirement. It will make use of heap data structure for
memory management. The required memory space can be allocated and
deallocated from heap memory. It is mainly used in pointers. Four types of
the pre-defined function that are used to dynamically allocate the memory
are given below:
■ malloc()
■ calloc()
■ realloc()
■ free()
11. Explain about getch() function in a C++ program. How it is different from
getche() function?
The getch() is a pre-defined library function in C++ that is used to receive a single input
character from the keyboard, and it holds the screen until it does not receive any character
from standard input. This function does not require any arguments and it is defined under
the “conio.h” header file.
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<"Enter the character:"<<endl;
getch();
}
This program holds the output screen until you press any character on the keyboard.
The only difference between these two functions is getch() does not echo the character to
the screen whereas getche() does.
12. What is meant by the Friend function in C++?
● A friend() function is a function that has access to private and protected members of
another class i.e., a class in which it is declared as a friend. It is possible to declare
a function as a friend function with the help of the friend keyword.
● Syntax:
class class_name
{
//Statements
friend return_type function_name();
}
13. What is normalization in the database?
● Normalization(data normalization or database normalization) is the technique of data
organization in the database to minimize data redundancy and improve data
integrity. Through database normalization, we can organize the data in tables and
columns, and also we can define a relationship between these tables or columns.
● Below are the commonly used normalization forms:
○ First Normal Form(1NF)
○ Second Normal Form(2NF)
○ Third Normal Form(3NF)
○ Boyce-Codd Normal Form(BCNF)
○ Fourth Normal Form(4NF)
○ Fifth Normal Form(5NF)
14. Can you give differences for the Primary key and Unique key in SQL?

Primary key Unique Key

It is a unique identifier for each row of a It is a unique identifier for table rows in the
table. absence of a Primary key.

A single Primary key is allowed in a table. More than one Unique Key is allowed in a
table.

NULL value or duplicate value is not It can have a single NULL value but a
permitted. duplicate value is not permitted.

When we define a Primary key, a clustered When we define a Unique key, a non-
index is automatically created if it does not clustered index is created by default to
already exist on the table. enforce a UNIQUE constraint.

15. What is Pandas in Python?


● Pandas is an open-source software library developed for Python and is useful in
data manipulation and analysis. It provides plenty of data structures and operations
such as modification of numerical tables and time series. It can deal with different
types of files and is considered to be one of the important tools to have a grip on.
● Some of the attributes or methods provided by Pandas are:
○ axes: It returns a row axis label list.
○ empty: It returns true if the series is empty otherwise it returns false.
○ size: It returns the count of elements in the underlying data.
○ values: It returns the series as ndarray.
○ head(): It returns the n rows from the beginning of a data frame or series.
○ tail(): Returns the n rows from the end of a data frame or series.
16. What is a classifier in Python?
A classifier is an algorithm that predicts the class of an input element on the basis of a set of
features. Usually, it will make use of training data(large datasets used to train an algorithm
or machine learning model) to obtain understand-ability regarding the relation between input
variables and class. It is mainly used in machine learning and supervised learning.
Example: A classifier can be used to predict the soap category depending on its
characteristics, which means its “features”. These features may include its fragrance,
appearance, color, etc. A machine learning classifier could potentially be used to predict
that soap with a round shape and brown color along with a strong fragrance of sandalwood
is a Mysore Sandal soap.
17. What is the difference between dictionary and tuple in Python?

Dictionary Tuple

A dictionary is an unordered data collection A tuple is an ordered data collection.


in which data will be stored in the form of
key-value pairs.

Elements are accessed using key values. Elements are accessed using numeric
index values.

Dictionary can have any number of values. A tuple can have only a pre-defined number
of values.

It is used as a model object. It is useful for returning multiple values from


a function.

18. What is a map() function in Python?


● In Python, the map() function is useful for applying the given function on every
element of a specified iterable(list, tuple, etc.).
● Syntax for map() function is: map(func, itr)
Where func is a function applied to every element of an iterable and itr is iterable
which is to be mapped. An object list will be returned as a result of map() function
execution.
● Example:
def addition(n):
return n+n
number=(10, 20, 30, 40)
res= map(addition, number)
print(list(res))
Output: 20, 40, 60, 80
In the above code segment, we are passing the addition() function and number as
parameters to the map() function. Now, the addition() function will be applied to every
element of the number tuple, each item value is added with the same item value and the
result generated will be stored in the res list.
19. What is XML?
XML(Extensible Markup Language) is a mark-up language that states rules for document
encoding formatting in such a way that it can be easily understood by both humans and
machines. It is useful to describe the data, develop information formats, and share
structured data through the internet.
20. Write a C++ program for generating the Fibonacci series.
The Fibonacci series is a number sequence in which each number is the sum of the
previous two numbers. Fibonacci series will have 0 followed by 1 as its first two numbers.
The Fibonacci series is as follows:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55....
The below-given program will display the Fibonacci series of n range of numbers given by
the user. If the entered range value is 1, the num1 value will be printed, i.e., 0. If the entered
range value is 2, num1 and num2 values will be printed, i.e., 0 and 1. If entered range value
is n, num1 and num2 value will be printed. Along with that, each next term will be calculated
based on the addition of the previous two numbers and this process continues until it
generates n numbers in a Fibonacci series.
#include<iostream.h>
#include<conio.h>
void main()
{
int num1,num2,nextnum,n,i;
cout<<"Enter the value for range:"; //Fibonacci series range value will be inputted
cin>>n;
num1=0;
num2=1;
cout<<"Fibonacci series is:"<<endl;
if(n==1)
cout<<num1<<endl; //Single value will be printed if range value is 1
else if(n==2)
cout<<num1<<"\t"<<num2<<endl; //Two values will be printed if the range value is two
else
{
cout<<num1<<"\t"<<num2<<"\t";
for(i=3;i<=n;i++) //Fibonacci series will be printed based on range limit
{
nextnum=num1+num2;
cout<<nextnum<<"\t";
num1=num2;
num2=nextnum;
}
}
getch();
}

JAVA

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:
○ First, the Java source code (.java) conversion to byte code (.class) occurs
with the help of the javac compiler.
○ 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.
○ 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.
○ 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 It is a binary operator in Java.


class.

The .equals() Method is present in the It cannot be modified. They always


Object class, so we can override our compare the HashCode.
custom .equals() method in the custom
class, for objects comparison.

This method is used for checking the This operator is used for comparing
equality of contents between two objects as addresses (or references), i.e checks if both
per the specified business logic. the objects are pointing to the same
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:
○ When a variable is declared as final in Java, the value can’t be modified once
it has been assigned.
○ If any value has not been assigned to that variable, then it can be assigned
only by the constructor of the class.
● final method:
○ A method declared as final cannot be overridden by its children's classes.
○ 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:
○ 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:
○ Accessing data members of parent class when the member names of the
class and its child subclasses are same.
○ To call the default and parameterized constructor of the parent class inside
the child class.
○ 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.
○ 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;

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

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

Sara Amanora Park Town Until the Day I Die Ms.


94 (Emily Carpenter),
Inception
(Christopher Nolan)

Ansh 62nd Sector A-10 The Alchemist Mr.


(Paulo Coelho),
Inferno (Dan Brown)

Sara 24th Street Park Beautiful Bad (Annie Mrs.


Avenue Ward), Woman 99
(Greer Macallister)

Ansh Windsor Street 777 Dracula (Bram Mr.


Stoker)

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 Until the Day I Die Ms.


94 (Emily Carpenter)

Sara Amanora Park Town Inception Ms.


94 (Christopher Nolan)

Ansh 62nd Sector A-10 The Alchemist Mr.


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

Sara 24th Street Park Beautiful Bad (Annie Mrs.


Avenue Ward)

Sara 24th Street Park Woman 99 (Greer Mrs.


Avenue Macallister)

Ansh Windsor Street 777 Dracula (Bram Mr.


Stoker)

● 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 Ms.


94

2 Ansh 62nd Sector A-10 Mr.

3 Sara 24th Street Park Mrs.


Avenue

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 1


94
2 Ansh 62nd Sector A-10 2

3 Sara 24th Street Park 3


Avenue

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.
○ Inline: returns a table data type based on a single SELECT statement.
○ 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 $$
DELIM
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 '____'

You might also like