PADA Role TECH Questions
PADA Role TECH Questions
● 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
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
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
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.
#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?
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.
Dictionary Tuple
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.
JAVA
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 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.");
}
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.
}
}
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.
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)
);
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.
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.
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
1 Ms.
2 Mr.
3 Mrs.
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 '___%'