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

Technical Interview Qns & Ans Blueprint

Technical Interview Qns & Ans Blueprint

Uploaded by

953622244004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views44 pages

Technical Interview Qns & Ans Blueprint

Technical Interview Qns & Ans Blueprint

Uploaded by

953622244004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

TECHNICAL INTERVIEW

( Java ☕)
1. What is Java?

Definition:

Java is a high-level, object-oriented, and platform-independent programming


language developed by Sun Microsystems, now owned by Oracle. It follows the
'Write Once, Run Anywhere' principle, meaning that Java programs can run on any
device with a Java Virtual Machine (JVM).

Explanation:

A Java application developed on a Windows machine can run on a Mac, Linux, or


any other platform with the JVM installed.

2. What are the key features of Java?

Definition:

Java is platform-independent due to the JVM (Write Once, Run Anywhere). It’s
object-oriented, secure (e.g., runtime exceptions handling), and supports
multi-threading for concurrent programming.

Explanation:

Java is commonly used in building banking systems where security and concurrency
are essential.

3. What is the difference between JDK, JRE, and JVM?

Definition:

JDK: Development kit with tools like compiler (javac), debugger, and libraries.

JRE: Execution environment containing libraries and JVM.

JVM: Converts bytecode into machine code.


Explanation:

The JDK is like a full kitchen with tools and ingredients to cook a dish (write a
program), the JRE is like having pre-packed ingredients (ready to execute programs),
and the JVM is the chef that cooks (executes) the dish.

4. What is the difference between static and instance variables?

Definition:

Static variables are shared among all instances of a class, while instance variables
are unique to each object.

Explanation:

In a class University, universityName is static (shared by all students), while


studentID is an instance variable (unique to each student).

5. What is inheritance in Java? How does it work?

Definition:

Inheritance is a property of Object-Oriented Programming that allows a class to


acquire properties of another (parent-child relationship). It promotes code reusability.

Explanation:

A class Dog can inherit from a class Animal. The Dog class will have access to
Animal's methods (like eat()), but it can also add its own methods, like bark().

6. What is polymorphism in Java? Explain with examples.

Definition:

Polymorphism is also the property of Object-Oriented Programming which means


many forms and allows objects to be treated as instances of their parent class, but
they can behave differently based on the subclass.

Two types:

Compile-time Polymorphism: Achieved through method overloading.

Runtime Polymorphism: Achieved through method overriding.


Explanation:

Compile-time: Overloading a method calculateArea() to handle different shapes


like square and rectangle.

Runtime: Overriding the speak() method in classes like Dog and Cat where each
class has its own implementation.

7. What is the difference between abstract classes and interfaces?

Definition:

Abstract classes provide a partial implementation with abstract methods, while


interfaces are contracts for behavior (all methods are public and abstract). Interfaces
support multiple inheritance, whereas abstract classes don’t.

Explanation:

Abstract Class is like a template for a vehicle, while Interface is like a contract that
requires any vehicle to implement methods like startEngine().

8. Can we overload the main() method in Java?

Definition:

Yes, you can overload the main( ) method, but the JVM always starts execution with
the main(String[] args) signature.

Explanation:

You can write multiple main() methods with different parameter lists, but only the
standard one will be executed by the JVM.

9. What is encapsulation? Why is it important?

Definition:

Encapsulation, the property of Object-Oriented Programming hides internal details


and exposes only necessary functionality. It’s achieved using private fields and public
getters/setters, ensuring security and modular code design.
Explanation:

In a Car class, the engine variable is private, and you use public getter and setter
methods to access or modify the engine state, ensuring proper control over the data.

10. What is the difference between "==" and .equals()?

Definition:

== compares object references (memory addresses). .equals() checks content. For


example, new String("Java") == new String("Java") is false, but .equals() returns true.

Explanation:

new String("Java") == new String("Java") would return false because


they are different objects in memory.

new String("Java").equals(new String("Java")) would return true


because the content of both strings is the same.

11. What is the difference between an abstract class and an interface in Java?

Definition:

Abstract class: Can have both abstract and concrete methods. Supports inheritance
but not multiple inheritance.

Interface: Contains only abstract methods (pre-Java 8) or default methods (Java 8+).
Supports multiple inheritance. Think of an abstract class as a blueprint with partial
implementation, and an interface as a strict contract.

Explanation:

Think of an abstract class like a vehicle blueprint that might have some predefined
methods, while an interface is like a contract that forces a class to implement certain
methods (like startEngine()).

12. What is a constructor in Java? Why is it used?

Definition:

A constructor initializes an object when it is created. It shares the class name and
has no return type.
Example Program:

public class Car {

String model;

Car(String model) {

this.model = model;

Car car1 = new Car("Tesla"); ← Object Creation

Explanation:

This code defines a Car class with an instance variable model to store the car's
model. The constructor Car(String model) initializes the model variable when a
Car object is created. For example, Car car1 = new Car("Tesla"); creates a
Car object with the model set to "Tesla". The constructor assigns this value to the
object's model instance variable.

13. What is the difference between this and super in Java?

Definition:

this refers to the current instance of the class. super refers to the parent class's
instance. Example: Using this to resolve instance variable conflicts and super to call
the parent class’s constructor or method.

Explanation:

this can be used to resolve conflicts between instance variables and method
names, while super is used to invoke the parent class constructor or method.

14. What is method overloading in Java?

Definition:

Method overloading allows multiple methods in a class with the same name but
different parameter lists.
Example Program:

void add(int a, int b) { return a + b; }

void add(double a, double b) { return a + b; }

Explanation:

This code demonstrates method overloading in Java, where two methods with the
same name add are defined but differ in parameter types. The first method takes two
int parameters and returns their sum, while the second method takes two double
parameters and returns their sum. This allows the same method name to handle both
integer and floating-point addition. The method to be called is determined by the type
of arguments passed.

15. What is method overriding in Java?

Definition:

Method overriding allows a subclass to provide its own implementation of a method


defined in a parent class. It ensures runtime polymorphism.

Example Program:

class Animal {

void sound() { System.out.println("Generic sound"); }

class Dog extends Animal {

void sound() { System.out.println("Bark"); }

Explanation:

This code demonstrates method overriding in Java, where the Dog class overrides
the sound() method of its parent class Animal. The sound() method in Animal
prints "Generic sound", while the overridden sound() method in Dog prints "Bark".
This allows the Dog class to provide its own specific implementation of the sound()
method.
16. What are the rules for overriding methods?

Definition:

The method must have the same name, return type, and parameters. The overriding
method cannot throw broader exceptions. It must not be less accessible (e.g., public
→ protected is not allowed).

Explanation:

Method overriding ensures that the subclass method behaves consistently with the
parent method by having the same name, return type, and parameters. Allowing
broader exceptions or more restrictive access would break the contract and introduce
inconsistencies. These rules maintain the integrity of the inheritance structure and
the principle of polymorphism.

17. What is the difference between compile-time and runtime polymorphism?

Definition:

Compile-time polymorphism: Achieved through method overloading. Resolved at


compile-time.

Runtime polymorphism: Achieved through method overriding. Resolved during


runtime.

Explanation:

Compile-time is like selecting an overloaded method based on parameters, and


runtime is like selecting an overridden method based on the object type.

18. What is the use of the final keyword in Java?

Definition:

Final variable: Prevents reassignment.

Final method: Prevents overriding.

Final class: Prevents inheritance.

Explanation:

Final variable: Once assigned a value, it cannot be reassigned (e.g., final int x
= 10;).
Final method: Prevents subclass methods from overriding it (e.g., final void
display() {}).

Final class: Prevents other classes from inheriting from it (e.g., final class
String {} prevents subclassing).

19. What is abstraction? How is it different from encapsulation?

Definition:

Abstraction hides implementation details and focuses on functionality (achieved


using abstract classes and interfaces). Encapsulation focuses on restricting direct
access to data.

Explanation:

Abstraction: A Car class might have a drive() method, but the internal workings
(engine, fuel) are hidden.

Encapsulation: The Car class has private fields like fuelLevel and provides
public methods like getFuelLevel() and setFuelLevel().

20. Explain the concept of a class and an object in Java.

Definition:

A class is a blueprint (e.g., a Car template with attributes like color, speed), while an
object is its real-world instance (e.g., a red Ferrari). Classes define properties and
behavior, and objects bring them to life.

Explanation:

Class: A Car class might have properties like color, speed, and methods like
accelerate(), brake().

Object: An object of the Car class could be a red Ferrari, where the color is "red"
and the speed is 0 initially. This object will use the methods like accelerate() to
change its speed.
( C++ 👨🏻‍💻)
21. What is C++?

Definition:

C++ is a general-purpose programming language that supports object-oriented,


procedural, and generic programming. It's widely used in system/software
development and game development.

Explanation:

Think of C++ as a powerful tool for building complex software systems, like a video
game or an operating system. It lets developers create reusable components that
interact with each other.

22. What is the difference between C++ and C?

Definition:

C++ is an extension of C that adds object-oriented programming features, such as


classes, inheritance, polymorphism, and encapsulation. C is procedural, focusing on
functions.

Explanation:

Imagine C as a manual for building a car. It's all about the steps (functions). C++ is
the same manual but with added instructions on designing car parts (classes) and
managing how parts interact with each other (polymorphism, inheritance).

23. What is the difference between struct and class in C++?

Definition:

The key difference is access control. In a struct, members are public by default,
while in a class, members are private by default.

Explanation:

Imagine a struct as a simple table where all the data is visible and accessible to
everyone. A class, on the other hand, is like a locked box where the data is hidden,
and you need keys (methods) to access it.
24. What are constructors and destructors in C++?

Definition:

A constructor is a special function that gets called when an object is created, while a
destructor is called when an object is destroyed.

Explanation:

Think of a constructor as the assembly line for building a car. When the car is
created, the constructor initializes it with specific features. A destructor is like the car
being dismantled when no longer needed.

25. What is operator overloading in C++?

Definition:

Operator overloading allows you to define how operators (like +, -, etc.) behave for
user-defined types.

Explanation:

In a real-world scenario, consider a calculator. When you press the "+" button, it
adds numbers, but when you press the "+" with strings, it concatenates them.
Operator overloading allows different types to behave differently.

26. What are virtual functions in C++?

Definition:

A virtual function is a function in a base class that can be overridden in a derived


class. It supports runtime polymorphism.

Explanation:

A "Shape" class might have a draw() function, but a derived "Circle" or "Rectangle"
class would have its own version of draw() that behaves differently.
27. What is the use of the new and delete keywords in C++?

Definition:

new is used to dynamically allocate memory, and delete is used to deallocate that
memory when it's no longer needed.

Explanation:

When you rent a car, you use new to get the car. When you're done, you use delete
to return the car and free up the space.

28. What is the difference between public, private, and protected access
specifiers?

Definition:

public members are accessible from anywhere, private members are accessible
only within the class, and protected members are accessible within the class and
derived classes.

Explanation:

Imagine a company. public members are accessible by all employees, private


members are restricted to the CEO, and protected members are accessible by
managers and above.

29. What is the purpose of a pointer in C++?

Definition:

A pointer holds the memory address of another variable, allowing indirect access to
data.

Explanation:

Think of a pointer as a map that leads to a location (memory). Instead of accessing


the place directly, you use the map (pointer) to get there.
30. What is a reference in C++?

Definition:

A reference is an alias for another variable, providing a way to access that variable
indirectly.

Explanation:

A reference is like calling someone by a nickname. The nickname refers to the same
person, just like a reference points to the same variable.

31. What is the difference between malloc() and new in C++?

Definition:

malloc() is a C function for memory allocation that doesn't call constructors, while
new is a C++ operator that allocates memory and calls the constructor.

Explanation:

Using malloc() is like buying a car without getting it equipped with the necessary
parts. new is like getting a car fully equipped and ready to drive.

32. What is a namespace in C++?

Definition:

A namespace is a way to group related classes, functions, and variables to avoid


naming conflicts.

Explanation:

Imagine a global library and a university library both having a book titled "C++
Basics". Using namespaces prevents confusion between the two.

33. What is the static keyword in C++?

Definition:

static can be used for variables and functions to limit their scope to the current file
or class. It can also be used to keep a variable's value between function calls.
Explanation:

A static variable in a function is like a memory bank that retains the amount of money
in a cash register after each customer leaves.

34. What is the difference between call by value and call by reference?

Definition:

Call by value: When calling by value, we send a duplicate of the parameter to the
functions. These duplicated values are given a new memory address, and any
modifications to these values have no impact on the variable used in the main code.

Call by reference: Here, we give a reference of the variable's address, and it uses
that address to find the actual argument that was used to call the function. Changes
to the parameter consequently have an effect on the passing argument.

Explanation:

Think of “call by value” as making a photocopy of a document and giving it to


someone: The photocopy represents the duplicate value. If the person makes
changes to the photocopy, the original document remains unaffected.

Think of “call by reference” as sharing the original document with someone: If they
make changes, those changes are reflected in the same document.

35. What is meant by copy constructor in C++?

Definition:

A copy constructor in C++ is a unique constructor used to duplicate an existing object


of the same class. It is called whenever an object is supplied a value, returned as a
value from a function, or initialised as a duplicate of another object.

Explanation:

Imagine a copy constructor as a photocopier that duplicates a document. The


original document represents the existing object, and the photocopied version
represents the new object created using the copy constructor. The two documents
have the same content (data), but any changes made to the photocopy do not affect
the original document.
36. What is inheritance in C++?

Definition:

Inheritance allows one class to acquire the properties and behaviors of another class.
It promotes code reusability.

Explanation:

A "Dog" class inherits from an "Animal" class. The "Dog" inherits basic properties
of an "Animal" (like being able to move or eat), but it also adds unique features like
barking.

37. What is polymorphism in C++?

Definition:

Polymorphism allows objects of different classes to be treated as objects of a


common base class, but they behave differently based on their actual class.

Explanation:

Imagine a remote control that can work with different devices like a TV or an air
conditioner. The remote sends the same signal (method), but each device reacts
differently (method override).

38. What is encapsulation in C++?

Definition:

Encapsulation is the concept of restricting direct access to certain data in a class and
providing public methods to access or modify that data.

Explanation:

Think of a bank account. The internal balance (data) is hidden from direct access,
and you use methods like deposit() or withdraw() to modify the balance safely.

39. What is Function Overriding?

Definition:

When a function of the same name, same arguments or parameters, and same
return type already present/declared in the base class is used in a derived class is
known as Function Overriding. It is an example of Runtime Polymorphism or Late
Binding which means the overridden function will be executed at the run time of the
execution.

Explanation:

When you visit the generic restaurant, you get standard dishes, but when you visit
the specialty restaurant, the overridden method ensures you receive specialty dishes
instead. The decision to execute the overridden method happens at runtime, based
on the restaurant type.

40. What is the difference between global and local variables?

Definition:

Global variables, such as a session id, are helpful for data that is generally constant
or that must be used by several functions in the code. On the other hand, a local
variable has a restricted scope. It exists only within the block in which it was
declared. When the block ends, the variable is destroyed, and its values are lost.

Explanation:

Global Variable (Ex: Session ID):

Think of a shopping website. A global session ID is generated when a user logs into
the site. This session ID is accessible to various functions, such as addToCart(),
checkout(), and viewOrderHistory(), ensuring the user's actions are tied to their
account throughout the session.

Local Variable (Ex: Cart Items in a Function):

Within the addToCart() function, a local variable like itemCount might be used to
temporarily store the count of items being added during that specific function call.
Once the function ends, this variable is no longer needed and is destroyed.
(C 🌐)
41. What is C?

Definition:

C is a general-purpose programming language that was developed in the 1970s and


is widely used for system and application software. It provides low-level access to
memory and is known for its efficiency.

Explanation:

Think of C as a toolset for building strong, foundational software components, like


constructing the engine of a car. It doesn’t handle all the complexities, but it gets the
most fundamental parts running.

42. What is the difference between C and C++?

Definition:

C is a procedural language, while C++ is an extension of C that supports


object-oriented programming (OOP) features like classes, inheritance, and
polymorphism.

Explanation:

C is like a basic blueprint for constructing a house, focusing on step-by-step


construction (procedural). C++ is like that blueprint, but with added design features
and instructions for creating reusable parts (object-oriented).

43. What are functions in C?

Definition:

Functions in C are blocks of code designed to perform specific tasks. They help in
breaking down a complex problem into simpler tasks.

Explanation:

A function is like a machine that takes input (parameters), performs some task
(processing), and gives output (return value). For example, a vending machine
(function) takes money (input), dispenses a drink (output).
44. What is a pointer in C?

Definition:

A pointer is a variable that stores the memory address of another variable, enabling
indirect access to its value.

Explanation:

A pointer is like an address of a house (variable). Instead of directly interacting with


the house, you can interact with the address (pointer) to get to it.

45. What is the difference between ++i and i++ in C?

Definition:

Both increment the value of i, but ++i increments first and then returns the value,
while i++ returns the value first and then increments.

Explanation:

Think of ++i as someone filling a cup (increment) and immediately handing it to you
(return value). i++ is like someone handing you the cup (return value) and then
refilling it (increment).

46. What is a structure in C?

Definition:

A structure is a user-defined data type that groups related variables of different types
into a single unit.

Explanation:

A structure is like a recipe card that contains ingredients of different types, such as
flour (int), sugar (float), and butter (char), bundled together to form a recipe.

47. What are arrays in C?

Definition:

An array is a collection of elements of the same data type stored in contiguous


memory locations.
Explanation:

An array is like a row of mailboxes (elements) where each mailbox (array element)
contains a specific piece of mail (data). All mailboxes are of the same size and type.

48. What is dynamic memory allocation in C?

Definition:

Dynamic memory allocation in C allows allocating memory during runtime using


functions like malloc(), calloc(), and realloc().

Explanation:

It’s like renting a car. You decide how much space you need (memory) at the time of
renting (runtime), and when you’re done, you return the car (memory deallocation).

49. What is the difference between strcpy() and strncpy() in C?

Definition:

strcpy() copies an entire string to another, while strncpy() copies up to a specified


number of characters, preventing buffer overflow.

Explanation:

strcpy() is like transferring an entire document into another folder, while strncpy() is
like copying only the first few pages to avoid overflowing the folder.

50. What is the difference between malloc() and calloc() in C?

Definition:

malloc() allocates memory but doesn't initialize it, whereas calloc() allocates
memory and initializes it to zero.

Explanation:

Think of malloc() as buying an empty box, and calloc() is like buying a box that
comes with everything inside it already sorted (initialized).
51. What is a NULL pointer in C?

Definition:

A NULL pointer is a pointer that doesn't point to any valid memory location.

Explanation:

A NULL pointer is like a GPS that doesn’t have a destination set. It’s not pointing to
any particular location.

52. What is recursion in C?

Definition:

Recursion is a function calling itself in order to solve a smaller instance of the same
problem.

Explanation:

Recursion is like a person in front of a mirror, where each mirror reflects the next
mirror. The person keeps seeing a smaller reflection of themselves (recursive call)
until they reach a base condition.

53. What is a macro in C?

Definition:

A macro in C is a preprocessor directive that defines a shorthand for a code snippet


or value.

Explanation:

A macro is like a shortcut key on a keyboard. Instead of typing the full sentence, you
press a key combination that inserts the predefined text (macro).

54. What are the storage classes in C?

Definition:

Storage classes define the lifetime, scope, and visibility of variables. The storage
classes are auto, register, static, and extern.
Explanation:

The storage class is like a filing system. auto is temporary, like a sticky note that
disappears after a while. static is like a permanent file in a drawer. extern is like
borrowing a file from another office.

55. What is a typedef in C?

Definition:

typedef is used to create new names for existing data types, making code more
readable.

Explanation:

typedef is like creating a nickname for a person. Instead of using their full name, you
can refer to them by a shorter, more familiar name.

56. What is a Preprocessor?

Definition:

A preprocessor is a software program that processes a source file before sending it


to be compiled. Inclusion of header files, macro expansions, conditional compilation,
and line control are all possible with the preprocessor.

Explanation:

Think of a movie production process. Before shooting a scene (compilation), a


pre-production team (preprocessor) prepares everything: Scripts (Header Files):
Import necessary scenes or dialogues (external libraries). Templates (Macros):
Reuse repeated props or dialogues for efficiency. Conditional Decisions
(Conditional Compilation): Decide what scenes to include based on the audience
(e.g., different endings for different regions).

57. Why doesn’t C support function overloading?

Definition:

Function overloading refers to the ability to define multiple functions with the same
name but with different parameters (in type, number, or both) within the same scope.
It allows the compiler to decide which function to call based on the arguments
passed.
C, however, does not support function overloading because it uses a simple
name-mangling mechanism for function names in the symbol table during
compilation. Each function in C is uniquely identified by its name only, without
considering its parameters. As a result, two functions with the same name would
conflict in the symbol table, causing an error.

Explanation:

Imagine a call center where each operator is identified by a single name (like
"Agent John"). If two people are named "John", the system would be confused
about which John should take the call because it doesn’t have any extra information
(like a department or role) to distinguish between them.

In contrast, in a more advanced system (like function overloading in C++), every


operator has a unique identifier, such as "John-Sales" or "John-Support", which
makes it clear who to contact.

58. What is typecasting in C?

Definition:

Typecasting in C is the process of converting a variable from one data type to


another. It can be classified into two types:

Implicit Typecasting (Type Conversion): The compiler automatically converts one


data type to another when needed (e.g., converting an int to float in arithmetic
operations).

Explicit Typecasting (Type Casting): The programmer explicitly specifies the


conversion using the syntax (type)variable, overriding the compiler's default behavior.

Explanation:

Imagine you are pouring liquid from one container into another. If the two containers
are compatible (e.g., both are bottles of similar size), no special effort is needed. This
is like implicit typecasting. If the containers are incompatible (e.g., a large jar into a
small glass), you’ll need to adjust or carefully measure the quantity. This resembles
explicit typecasting, where manual intervention is required.

59. What is Function Overriding?

Definition:

When a function of the same name, same arguments or parameters, and same
return type already present/declared in the base class is used in a derived class is
known as Function Overriding. It is an example of Runtime Polymorphism or Late
Binding which means the overridden function will be executed at the run time of the
execution.

Explanation:

When you visit the generic restaurant, you get standard dishes, but when you visit
the specialty restaurant, the overridden method ensures you receive specialty dishes
instead. The decision to execute the overridden method happens at runtime, based
on the restaurant type.

60. What is the meaning of #include in a C program?

Definition:

#include is a preprocessor directive in C used to include external files (such as


libraries or header files) into a C program. It tells the preprocessor to insert the
contents of the specified file into the source code before compilation. There are two
main types of #include:

#include <filename>: Includes a standard library or system header file.

#include "filename": Includes a user-defined header file (usually in the same


directory).

Explanation:

Think of #include like a reference or citation in a book. When writing a report, you
may refer to another book or research paper for additional information. Similarly, in a
C program, #include allows you to bring in external code or libraries so that you can
use their functionality without rewriting them.
( Python 🐍)
61. What is Python?

Definition:

Python is a high-level, interpreted, and general-purpose programming language


known for its readability, simplicity, and extensive libraries.

Explanation:

Python is often used for building web applications, like Instagram or Dropbox. Its
simplicity and readability allow developers to quickly create features like user login or
image

62. What are Python's key features?

Definition:

Python is an easy-to-learn language, with dynamic typing, automatic memory


management, and a large standard library

Explanation:

Think of Python as a toolbox for a carpenter. If you need a hammer, screwdrivers, or


a wrench, Python offers built-in tools (functions, modules) to help you. It can be used
in web development (Flask), data analysis (Pandas), and even automation
(Selenium).

63. What is a list in Python?

Definition:

A list is a mutable, ordered collection of items and they are versatile and can store
multiple types of data.

Explanation:

A list is like a shopping cart that can hold multiple items. You can add or remove
products (elements), and the list maintains their order.
64. What is a tuple in Python?

Definition:

A tuple is an immutable, ordered collection of items where they cannot be modified


after creation, making them ideal for fixed collections.

Explanation:

Imagine a set of coordinates (latitude, longitude) for a location on a map. These


values do not change once set, so a tuple is the ideal data type to store them.

65. What is the difference between list and tuple?

Definition:

The primary difference is that lists are mutable (can be changed), while tuples are
immutable (cannot be changed).

Explanation:

Think of a list as a grocery list you can edit, while a tuple is like a menu from a
restaurant that you can't change.

66. What is a dictionary in Python?

Definition:

A dictionary is an unordered collection of key-value pairs and it allows fast retrieval


based on a unique key.

Explanation:

A dictionary is like an address book, where you store names as keys and phone
numbers as values.

67. What is the use of self in Python?

Definition:

self refers to the instance of the class, allowing access to its attributes and methods.
Explanation:

Think of self as the reference to your personal notebook when you're writing down
notes about your life (attributes and behaviors). In a class, self allows you to refer to
the current object instance.

68. What is the difference between deepcopy and shallow copy?

Definition:

shallow copy creates a new object but does not copy nested objects, whereas deep
copy recursively copies nested objects.

shallow copy: Modifying a nested element in the copied object affects the original.

deepcopy: The original object remains unaffected after modifying the nested
elements.

Explanation:

Consider you have a notebook with pages, and you make a shallow copy. Both
notebooks share the same pages, so if you modify a page in one notebook, it
changes in both. A deep copy creates a completely separate notebook.

69. What are lambda functions in Python?

Definition:

Lambda functions are anonymous, small, and defined using the lambda keyword.

Explanation:

A lambda function is like a quick, one-off helper tool you use once in a while, like a
calculator for a quick sum.

70. What is the difference between a Set and Dictionary?

Definition:

Set: A set is a collection of unique, unordered elements. It does not allow duplicate
items, and elements cannot be accessed by indexing. Sets are useful for operations
like union, intersection, and difference.
Dictionary: A dictionary is a collection of key-value pairs, where each key is unique,
and each key maps to a corresponding value. Keys are immutable (like strings or
numbers), but values can be mutable or immutable.

Explanation:

A set is like a bag of unique coins. You can quickly check if a particular coin is
present in the bag, but the order of coins doesn't matter.

A dictionary is like a contact list on your phone. Each name (key) maps to a phone
number (value). You can quickly retrieve someone's phone number by looking up
their name.

71. What is a generator in Python?

Definition:

A generator is a special type of iterator that generates values on the fly using the
yield keyword.

Explanation:

A generator is like a vending machine that gives one item at a time. You ask for a
product, and the machine gives you one, instead of giving everything at once.

72. What is a pass in Python?

Definition:

In Python, pass is a statement that does nothing. It acts as a placeholder and is used
when a statement is syntactically required but no action is needed. This is especially
useful when writing code structures where the implementation is incomplete or
planned for later.

Explanation:

Think of pass as a reserved "to-do" note. For instance, in a meeting agenda, you
might allocate time for a discussion but decide to skip it for now. Similarly, pass
allows you to define a block of code that is temporarily empty, without causing a
syntax error.
73. In Python, how do you overload methods or constructors?

Definition:

In Python, method or constructor overloading refers to defining multiple methods or


constructors with the same name but different arguments. However, Python does not
natively support method or constructor overloading in the traditional sense, as seen
in languages like C++ or Java. Instead, Python achieves overloading behavior by:

Using default arguments in a single method or constructor.

Implementing logic to handle different types or numbers of arguments using


techniques like *args and **kwargs.

Explanation:

Think of a customer service desk where a single representative can handle different
kinds of requests based on the details provided by the customer. For example:

If a customer provides their name and ID, the representative processes their request.

If a customer provides only their name, the representative asks for additional
information.

74. What are Python’s exception handling mechanisms?

Definition:

Python's exception handling mechanism is a structured way to manage errors that


occur during program execution. Instead of terminating the program abruptly, Python
allows developers to "handle" these errors gracefully using a set of predefined
keywords: try, except, else, and finally.

Explanation:

Exception handling is like having a backup plan for unforeseen situations during code
execution. For example: Imagine you're withdrawing money from an ATM. If the
machine runs out of cash, it displays an error message instead of malfunctioning.
Similarly, in Python, exceptions provide a way to respond to errors without crashing
the program.
75. What is the purpose of the "init" method in Python?

Definition:

The __init__ method in Python is a special method (often called the constructor) that
is automatically invoked when a new object of a class is created. Its primary purpose
is to initialize the attributes of the object and set up any necessary data or
configurations.

Explanation:

Imagine registering for a gym membership.When a person registers, their name,


membership type, and fees need to be recorded. Every new member (an object of
the class) is initialized with these details when they join.

76. Explain list, dictionary, and tuple comprehension with an example.

Definition:

List Comprehension: A concise way to create lists by iterating over an iterable and
optionally applying conditions or transformations.

Dictionary Comprehension: A concise way to create dictionaries by iterating over


an iterable and constructing key-value pairs.

Tuple Comprehension: Python does not support a direct "tuple comprehension";


instead, it uses generator expressions for similar purposes.

Explanation:

List Comprehension: Imagine you want to calculate the areas of square tiles, each
with side lengths from 1 to 5. The list comprehension makes this calculation concise.

Dictionary Comprehension: Suppose you're a carpenter tracking wood pieces'


dimensions. The keys represent the length of each piece, and the values represent
its volume when the height and width are fixed.

Tuple Comprehension: Consider an energy management system monitoring


even-numbered houses for power consumption. The generator (similar to a tuple
comprehension) can efficiently process these house numbers without consuming
memory for all values at once.
77. What is the Python “with” statement designed for?

Definition:

The Python with statement is designed to simplify resource management, such as file
handling or database connections. It ensures that resources are properly acquired
and released (e.g., closing a file or releasing a lock) without requiring explicit cleanup
code, even if exceptions occur.

Explanation:

Consider a banking application where a database connection is established to log


transactions. Forgetting to close the connection could lead to data corruption. The
with statement ensures proper connection closure.

78. What are decorators in Python?

Definition:

Decorators in Python are functions or classes that modify the behavior of another
function, method, or class without permanently altering its source code. They allow
you to wrap another function (or class) to add functionality before or after its
execution.

Explanation:

Imagine you're building a restaurant management system, and you want to ensure
every order processing function logs the time of the request for auditing purposes.
Instead of adding logging code to every function, you can use a decorator to handle
this logging.

79. What are Python modules and packages?

Definition:

A module is a file containing Python code, while a package is a collection of modules.

Explanation:

A module is like a toolbox containing related tools, while a package is a collection of


toolboxes.
80. What is slicing in Python?

Definition:

Slicing in Python is a technique used to extract specific portions of sequences like


strings, lists, or tuples. It allows you to access a range of elements by specifying a
start, stop, and step value.

Explanation:

Imagine you have a long bookshelf filled with books, and you only want books 2
through 5 from the shelf. Instead of removing all the books and then picking the ones
you need, you can directly select only that range.

In Python, slicing works similarly by allowing you to extract just the portion of data
you need from a larger sequence without modifying the original data.
( SQL 🗄️)
81. What is SQL?

Definition:

SQL (Structured Query Language) is a standardized programming language used


to manage and manipulate relational databases. It is used to perform tasks like
querying data, updating records, and managing database structures.

Explanation:

Imagine you're working at an e-commerce company, and the company has a large
database containing customer information, orders, and products. To retrieve
customer data, place an order, or generate reports, SQL is used. For example, a
query like SELECT * FROM Customers WHERE country = 'USA'; helps you fetch
all customers from the USA.

82. What is a database?

Definition:

A database is a structured collection of data that is stored and managed


electronically. It allows for easy access, management, and updating of the data.
Databases are designed to store, retrieve, and manipulate data efficiently.

Explanation:

Think of a library system where information about books, authors, and members is
stored in a database. The library's database helps manage data like which books are
available, who has borrowed a book, and what the overdue fines are. By using a
DBMS, the library can easily retrieve data like the list of books by a specific author or
find out how many books a member has borrowed.

83. What is a JOIN in SQL?

Definition:

A JOIN is a SQL operation used to combine data from two or more tables based on a
related column between them.

The most common types of JOINs are:

INNER JOIN: Returns only the rows that have matching values in both tables.
LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and
matching rows from the right table, with NULLs where no match exists.

RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and
matching rows from the left table, with NULLs where no match exists.

FULL JOIN (or FULL OUTER JOIN): Returns rows when there is a match in one of
the tables; NULLs where there is no match.

Explanation:

Think of a library system with two tables: one for Books and another for Authors. If
you wanted to find out which author wrote which book, you'd use a JOIN to combine
the data from both tables.

84. What are aggregate functions in SQL?

Definition:

Aggregate functions are functions that perform a calculation on a set of values and
return a single result.

Common aggregate functions include:

COUNT(): Counts the number of rows.

SUM(): Returns the sum of a numeric column.

AVG(): Returns the average value of a numeric column.

MIN(): Returns the smallest value in a set.

MAX(): Returns the largest value in a set. These functions are often used with the
GROUP BY clause to summarize data.

Explanation:

In a retail store, you might want to find the total sales, average price of items, and the
number of items sold during a specific time period. Using aggregate functions like
SUM(), AVG(), and COUNT(), you can calculate these values

85. What is the difference between WHERE and HAVING clauses?

Definition:

Both WHERE and HAVING are used to filter records in SQL, but they are used in
different contexts.
WHERE: Filters rows before any grouping is done. It is used to filter rows from a
table before any aggregate functions are applied.

HAVING: Filters records after grouping has been done. It is typically used with
aggregate functions to filter groups of records.

Explanation:

If you have a Sales table and want to find all employees who have made more than
$10,000 in sales, you'd use WHERE. However, if you're grouping sales data by
employee and want to filter groups with sales greater than $10,000, you'd use
HAVING.

86. What is Normalization?

Definition:

Normalization is the process of organizing data in a database to reduce redundancy


and dependency by dividing large tables into smaller ones and defining relationships
between them.

Explanation:

Consider an online shopping platform with a database containing information about


customers, orders, and products. In the first version of the database, all customer
and product information might be stored in a single table. This is inefficient and prone
to data redundancy (e.g., if a customer orders multiple products, their information is
repeated). By normalizing the database (splitting it into separate tables for
customers, orders, and products), we ensure that customer data is stored only once,
minimizing redundancy and improving data integrity.

87. What is a primary key in SQL?

Definition:

A primary key is a unique identifier for a record in a table, ensuring that each record
is distinct and identifiable.

Explanation:

In an Employees table, each employee needs a unique identifier. A primary key like
employee_id ensures that each employee record is distinct (unique).
88. What is a foreign key in SQL?

Definition:

A foreign key is a field (or combination of fields) in one table that uniquely identifies
a row of another table.

Explanation:

Consider a database with two tables: Orders and Customers. The Orders table has
a column customer_id that refers to the Customers table's id. This establishes a
relationship between the two tables. The customer_id in the Orders table is a
foreign key.

89. What is a subquery in SQL?

Definition:

A subquery is a query nested inside another query, which can be used to return a
value that will be used in the outer query.

Subqueries can be used in various parts of an SQL statement, such as in the


SELECT, INSERT, UPDATE, or DELETE clauses.

There are two types of subqueries:

Single-row subquery: Returns a single value.

Multiple-row subquery: Returns multiple values. Subqueries can be placed in


WHERE, FROM, or SELECT clauses, depending on the use case.

Explanation:

In an e-commerce database, you may want to find the orders placed by customers
who have spent more than $1000. You could first write a subquery to find the
customers who spent more than $1000 and then use that subquery in the outer query
to find their orders.

90. What is the difference between DELETE, TRUNCATE, and DROP?

Definition:

DELETE: Removes rows from a table based on a condition.

TRUNCATE: Removes all rows from a table but does not log individual row deletions.

DROP: Removes a table or database entirely from the system.


Explanation:

DELETE: You want to remove all Orders from a specific customer but keep the rest
of the data intact.

TRUNCATE: You want to remove all rows from the Orders table quickly, without
logging individual row deletions.

DROP: You want to completely remove the Orders table and all its data from the
database.

91. What is an index in SQL?

Definition:

An index is a data structure used to improve the speed of data retrieval operations
on a table at the cost of additional space.

Explanation:

Imagine you have a Customers table with millions of records, and you frequently
query the table to find customers by their email. To speed up this search, you could
create an index on the email column.

92. What are SQL constraints?

Definition:

SQL constraints are rules applied to columns or tables to ensure the accuracy and
integrity of data.

Common SQL constraints include:

NOT NULL: Ensures that a column cannot have NULL values.

UNIQUE: Ensures all values in a column are unique.

PRIMARY KEY: Uniquely identifies a record in a table.

FOREIGN KEY: Ensures the value in one table corresponds to a valid record in
another table.

CHECK: Ensures that values in a column meet a specified condition.

DEFAULT: Specifies a default value for a column if no value is provided.


Explanation:

In an online banking system, you might want to ensure that account balances cannot
be negative. You can use a CHECK constraint to enforce this

93. What is a transaction in SQL?

Definition:

A transaction is a sequence of operations performed as a single unit of work,


ensuring that all operations are completed successfully or none at all.

Transactions ensure data integrity in a database. They follow the ACID properties
(Atomicity, Consistency, Isolation, Durability) to guarantee that a transaction is
completed successfully or rolled back if an error occurs.

Explanation:

In a banking application, transferring money between two accounts requires multiple


steps (decreasing balance from one account, increasing balance in another). These
steps need to be performed as a single transaction to ensure data consistency. If any
step fails, the transaction can be rolled back to maintain consistency

94. What is the GROUP BY clause in SQL?

Definition:

The GROUP BY clause is used in SQL to group rows that have the same values into
summary rows.

Explanation:

In a sales database, you may want to calculate the total sales per product category.
You would group the data by category and then use an aggregate function like SUM
to calculate the total sales.

95. What is the difference between UNION and UNION ALL in SQL?

Definition:

UNION: Combines the results of two or more queries and removes duplicate rows.

UNION ALL: Combines the results of two or more queries but does not remove
duplicates.
Explanation:

Suppose you have two tables: OnlineSales and OfflineSales. You want to combine
both tables to get a list of all sales, but you want to exclude duplicates. You would
use UNION. If you want to include duplicates, you would use UNION ALL.

96. Explain list, dictionary, and tuple comprehension with an example.

Definition:

CHAR is best used for data that has a consistent length, such as country codes (e.g.,
"IN", "US"), fixed-length IDs, etc.

VARCHAR2 is best used for data with variable lengths, such as names, addresses,
or descriptions.

Explanation:

Imagine you have a customer database with a column for storing state codes (2
characters) and a column for storing customer names.

State Code (CHAR): Since state codes are always 2 characters (e.g., "NY", "TX"),
you would use CHAR(2) for the state code. This ensures that even if a code is 1
character long (e.g., "A"), it will still occupy 2 characters and pad with a space (e.g.,
"A ").

Customer Name (VARCHAR2): For a customer's name, the length varies from
person to person (e.g., "John" to "Alexander Smith"). You would use VARCHAR2 to
save space by only using the exact number of characters needed to store the name
without padding.

97. What is a view in SQL?

Definition:

A view is a virtual table based on the result of a SQL query. It does not store data
physically but displays data from one or more tables.

Explanation:

In a university database, you might have tables for Students, Courses, and
Enrollments. To simplify querying, you create a view that combines information from
these tables to show a list of students with their courses.

98. What is the difference between SQL and MySQL?


Definition:

SQL (Structured Query Language) is a programming language used to manage and


manipulate relational databases. It is used for querying, inserting, updating, and
deleting data in a database.

MySQL is a specific implementation of a relational database management system


(RDBMS) that uses SQL as its query language.

Explanation:

SQL is like the English language that helps us communicate with the database,
while MySQL is like a tool or machine that executes the instructions written in SQL.

99. What is the difference between SQL and NoSQL databases?

Definition:

SQL databases are relational databases that use structured tables to store data.
They follow a predefined schema and are best suited for transactional data.

NoSQL databases are non-relational and store unstructured data. They do not have
a fixed schema and are designed to scale out horizontally.

Explanation:

If you were to store data for an online retail store, SQL would be best for storing
order details (structured, with a clear relationship between customers and orders),
whereas NoSQL would be better for storing user-generated content, like
comments or logs, where the data structure can change over time.

100. What is the difference between MySQL and NoSQL?

Definition:

MySQL is a relational database management system (RDBMS) that uses SQL for
querying data and organizes data in tables with rows and columns.

NoSQL is a broad category of databases designed to handle unstructured or


semi-structured data, which includes document-based, key-value, column-family, and
graph databases.

Explanation:

MySQL would be suitable for an e-commerce platform's transactional data (like


user accounts, orders), while NoSQL is better suited for social media platforms
where data (like user posts and interactions) can vary greatly in structure and size.
101. What are the key differences between MySQL and PostgreSQL?

Definition:

MySQL is an open-source relational database management system known for its


speed and reliability.

PostgreSQL is an open-source RDBMS known for its advanced features like support
for JSON data types, full-text search, and complex queries.

NoSQL databases are non-relational and store unstructured data. They do not have
a fixed schema and are designed to scale out horizontally.

Explanation:

For a simple website, MySQL may be preferred for its simplicity and speed, but for
an enterprise application that requires complex data relationships, large datasets,
or advanced analytics, PostgreSQL may be a better choice due to its richer set of
features.
( DSA 📟)
102. What is Binary Search?

Definition:

Binary search is an efficient algorithm for finding an item from a sorted list by
repeatedly dividing the search interval in half. If the value of the search key is less
than the item in the middle, the search continues in the lower half, or in the upper half
if the value is greater.

Explanation:

Consider looking for a name in a phone book. Instead of going through each name
one by one, you would start in the middle of the phone book, check if the name
you're looking for is before or after, and continue halving the search space until you
find the name.

103. What is Bubble Sort?

Definition:

Bubble sort is a simple comparison-based sorting algorithm where each pair of


adjacent items is compared and swapped if they are in the wrong order. This process
is repeated until the list is sorted.

Explanation:

Think of sorting players by score in a game. Starting with the first player, you
compare each pair of players, and if a higher score is found, you swap their
positions. You repeat this process until the players are arranged in descending order.

104. What is Selection Sort?

Definition:

Selection sort is a sorting algorithm that repeatedly selects the smallest (or largest,
depending on sorting order) element from the unsorted portion and swaps it with the
first unsorted element.
Explanation:

Consider organizing a line of people by height. You start with the first person, find
the shortest person in the group, and swap positions. Then, you repeat this process
for the next person until everyone is arranged by height.

105. What is Insertion Sort?

Definition:

Insertion sort is a simple sorting algorithm where the list is built one item at a time. It
takes each element from the unsorted portion and inserts it into its correct position in
the sorted portion.

Explanation:

Think of sorting playing cards. When you pick up a new card, you place it in the
correct position among the cards already in your hand, keeping the hand sorted at all
times.

106. What is Merge Sort?

Definition:

Merge sort is a divide-and-conquer algorithm that splits the list into halves,
recursively sorts each half, and then merges the sorted halves to produce the sorted
list.

Explanation:

Imagine you have two sorted lists of books by genre (one for science and one for
history). Merge sort combines these lists into one sorted list by alternating the books
from each genre.

107. What is Linear Search?

Definition:

Linear search is a simple algorithm that checks every element in the list until the
target element is found or the entire list has been searched.

Explanation:

Searching for a particular ingredient in your kitchen cupboard by checking each


shelf one by one until you find it.
108. What is a Stack?

Definition:

A stack is a linear data structure that follows the Last In First Out (LIFO) principle,
where elements are added and removed from the top of the stack.

Explanation:

Think of a stack of plates. The last plate placed on top of the stack is the first one to
be taken off.

109. What is a Queue?

Definition:

A queue is a linear data structure that follows the First In First Out (FIFO) principle,
where elements are added at the rear and removed from the front.

Explanation:

A line at a movie theater is a queue. The first person to get in line is the first one to
be served.

110. How does QuickSort Work?

Definition:

QuickSort is a divide-and-conquer sorting algorithm that selects a pivot element,


partitions the array around the pivot, and recursively sorts the subarrays.

Explanation:

Think of sorting a group of people by age. You pick a "pivot" person, and everyone
older than them goes to one side, and everyone younger goes to the other side. You
repeat this process for each group.
111. What is a Dequeue?

Definition:

A dequeue (or double-ended queue) is a data structure that allows insertion and
deletion of elements from both ends, either from the front or the back.

Explanation:

A waiting line at a customer service counter where customers can either join the
line at the front or leave the line from the back.
CODING QUESTIONS FREQUENTLY ASKED IN
TECHNICAL INTERVIEWS

➢ Fibonnaci Series
➢ Armstrong Number
➢ Palindrome Number
➢ Palindrome String
➢ Reverse a String
➢ Reverse a Number
➢ Factorial of a number
➢ Prime or not
➢ Perfect Number or not
➢ Two Strings are Anagram or not
➢ Calculate frequency of characters in a String
➢ Maximum element in an Array
➢ Minimum element in an Array
➢ Reverse an Array
➢ Second Largest element in an Array
➢ Second Smallest element in an Array
➢ Sort an Array
➢ Missing number in an Array
➢ Duplicate in an Array
➢ Remove all characters from string except alphabets

You might also like