5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Search...
Python Course Python Tutorial Interview Questions Python Quiz Python Glossary Python Proje
Python Interview Questions and Answers
Last Updated : 01 May, 2025
Python is the most used language in top companies such as Intel, IBM,
NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many
more because of its simplicity and powerful libraries. To crack their
Online Assessment and Interview Rounds as a Python developer, we
need to master important Python Interview Questions. We have
prepared a list of the Top 50 Python Interview Questions along with
their answers to ace interviews.
Python Interview Questions for Freshers
1. Is Python a compiled language or an interpreted language?
Please remember one thing, whether a language is compiled or
interpreted or both is not defined in the language standard. In other
words, it is not a properly of a programming language. Different Python
distributions (or implementations) choose to do different things (compile
or interpret or both). However the most common implementations like
CPython do both compile and interpret, but in different stages of its
execution process.
Compilation: When you write Python code and run it, the source
code (.py files) is first compiled into an intermediate form called
bytecode (.pyc files). This bytecode is a lower-level representation of
your code, but it is still not directly machine code. It’s something that
the Python Virtual Machine (PVM) can understand and execute.
Interpretation: After Python code is compiled into bytecode, it is
executed by the Python Virtual Machine (PVM), which is an
interpreter. The PVM reads the bytecode and executes it line-by-line
at runtime, which is why Python is considered an interpreted
language in practice.
[Link] 1/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Some implementations, like PyPy, use Just-In-Time (JIT) compilation,
where Python code is compiled into machine code at runtime for faster
execution, blurring the lines between interpretation and compilation.
2. How can you concatenate two lists in Python?
We can concatenate two lists in Python using the +operator or the
extend() method.
1. Using the + operator:
This creates a new list by joining two lists together.
1 a = [1, 2, 3]
2 b = [4, 5, 6]
3 res = a + b
4 print(res)
Output
[1, 2, 3, 4, 5, 6]
2. Using the extend() method:
This adds all the elements of the second list to the first list in-place.
1 a = [1, 2, 3]
2 b = [4, 5, 6]
3 [Link](b)
4 print(a)
Output
[1, 2, 3, 4, 5, 6]
3. Difference between for loop and while loop in Python
For loop: Used when we know how many times to repeat, often with
lists, tuples, sets, or dictionaries.
[Link] 2/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
While loop: Used when we only have an end condition and don’t
know exactly how many times it will repeat.
1 for i in range(5):
2 print(i)
3
4 c = 0
5 while c < 5:
6 print(c)
7 c += 1
4. How do you floor a number in Python?
To floor a number in Python, you can use the [Link]() function,
which returns the largest integer less than or equal to the given
number.
floor() method in Python returns the floor of x i.e., the largest integer
not greater than x.
Also, The method ceil(x) in Python returns a ceiling value of x i.e.,
the smallest integer greater than or equal to x.
1 import math
2
3 n = 3.7
4 F_num = [Link](n)
5
6 print(F_num)
Output
5. What is the difference between / and // in Python?
/ represents precise division (result is a floating point number) whereas
// represents floor division (result is an integer). For Example:
1 print(5//2)
[Link] 3/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
2 print(5/2)
6. Is Indentation Required in Python?
Yes, indentation is required in Python. A Python interpreter can be
informed that a group of statements belongs to a specific block of code
by using Python indentation. Indentations make the code easy to read
for developers in all programming languages but in Python, it is very
important to indent the code in a specific order.
Python Indentation
7. Can we Pass a function as an argument in Python?
Yes, Several arguments can be passed to a function, including objects,
variables (of the same or distinct data types) and functions. Functions
can be passed as parameters to other functions because they are
objects. Higher-order functions are functions that can take other
functions as arguments.
1 def add(x, y):
2 return x + y
3
4 def apply_func(func, a, b):
5 return func(a, b)
6
7 print(apply_func(add, 3, 5))
[Link] 4/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
The add function is passed as an argument to apply_func, which applies
it to 3 and 5.
8. What is a dynamically typed language?
In a dynamically typed language, the data type of a variable is
determined at runtime, not at compile time.
No need to declare data types manually; Python automatically
detects it based on the assigned value.
Examples of dynamically typed languages: Python, JavaScript.
Examples of statically typed languages: C, C++, Java.
Dynamically typed languages are easier and faster to code.
Statically typed languages are usually faster to execute due to type
checking at compile time.
Example:
x = 10 # x is an integer
x = "Hello" # Now x is a string
Here, the type of x changes at runtime based on the assigned value
hence it shows dynamic nature of Python.
9. What is pass in Python?
The pass statement is a placeholder that does nothing.
It is used when a statement is syntactically required but no code
needs to run.
Commonly used when defining empty functions, classes or loops
during development.
1 def fun():
2 pass # Placeholder, no functionality yet
3
4 # Call the function
5 fun()
Here, fun() does nothing, but the code stays syntactically correct.
[Link] 5/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
10. How are arguments passed by value or by reference in
Python?
Python’s argument-passing model is neither “Pass by Value” nor
“Pass by Reference” but it is “Pass by Object Reference”.
Depending on the type of object you pass in the function, the
function behaves differently. Immutable objects show “pass by value”
whereas mutable objects show “pass by reference”.
You can check the difference between pass-by-value and pass-by-
reference in the example below:
1 def call_by_val(x):
2 x = x * 2
3 print("value updated to", x)
4 return
5
6 def call_by_ref(b):
7 [Link]("D")
8 print("list updated to", b)
9 return
10
11 a = ["E"]
12 num = 6
13
14 call_by_val(num)
15
16 call_by_ref(a)
Output
value updated to 12
list updated to ['E', 'D']
11. What is a lambda function?
A lambda function is an anonymous function. This function can have any
number of parameters but, can have just one statement.
[Link] 6/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
In the example, we defined a lambda function(upper) to convert a string
to its upper case using upper().
1 s1 = 'GeeksforGeeks'
2
3 s2 = lambda func: [Link]()
4 print(s2(s1))
Output
GEEKSFORGEEKS
12. What is List Comprehension? Give an Example.
List comprehension is a way to create lists using a concise syntax. It
allows us to generate a new list by applying an expression to each item
in an existing iterable (such as a list or range). This helps us to write
cleaner, more readable code compared to traditional looping techniques.
For example, if we have a list of integers and want to create a new list
containing the square of each element, we can easily achieve this using
list comprehension.
1 a = [2,3,4,5]
2 res = [val ** 2 for val in a]
3 print(res)
Output
[4, 9, 16, 25]
13. What are *args and **kwargs?
*args: The special syntax *args in function definitions is used to pass
a variable number of arguments to a function. Python program to
illustrate *args for a variable number of arguments:
1 def fun(*argv):
2 for arg in argv:
[Link] 7/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
3 print(arg)
4
5 fun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output
Hello
Welcome
to
GeeksforGeeks
**kwargs: The special syntax **kwargs in function definitions is used
to pass a variable length argument list. We use the name kwargs
with the double star **.
1 def fun(**kwargs):
2 for k, val in [Link]():
3 print("%s == %s" % (k, val))
4
5
6 # Driver code
7 fun(s1='Geeks', s2='for', s3='Geeks')
Output
s1 == Geeks
s2 == for
s3 == Geeks
14. What is a break, continue and pass in Python?
Break statement is used to terminate the loop or statement in which
it is present. After that, the control will pass to the statements that
are present after the break statement, if available.
Continue is also a loop control statement just like the break
statement. continue statement is opposite to that of the break
statement, instead of terminating the loop, it forces to execute the
next iteration of the loop.
[Link] 8/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Pass means performing no operation or in other words, it is a
placeholder in the compound statement, where there should be a
blank left and nothing has to be written there.
15. What is the difference between a Set and Dictionary?
A Python Set is an unordered collection data type that is iterable,
mutable and has no duplicate elements. Python’s set class
represents the mathematical notion of a set.
Syntax: Defined using curly braces {} or the set() function.
my_set = {1, 2, 3}
Dictionary in Python is an ordered (since Py 3.7) [unordered (Py 3.6 &
prior)] collection of data values, used to store data values like a map,
which, unlike other Data Types that hold only a single value as an
element, Dictionary holds key:value pair. Key-value is provided in the
dictionary to make it more optimized.
Syntax: Defined using curly braces {} with key-value pairs.
my_dict = {"a": 1, "b": 2, "c": 3}
16. What are Built-in data types in Python?
The following are the standard or built-in data types in Python:
Numeric: The numeric data type in Python represents the data that
has a numeric value. A numeric value can be an integer, a floating
number, a Boolean, or even a complex number.
Sequence Type: The sequence Data Type in Python is the ordered
collection of similar or different data types. There are several
sequence types in Python:
Python String
Python List
Python Tuple
Python range
[Link] 9/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Mapping Types: In Python, hashable data can be mapped to random
objects using a mapping object. There is currently only one common
mapping type, the dictionary and mapping objects are mutable.
Python Dictionary
Set Types: In Python, a Set is an unordered collection of data types
that is iterable, mutable and has no duplicate elements. The order of
elements in a set is undefined though it may consist of various
elements.
17. What is the difference between a Mutable datatype and an
Immutable data type?
Mutable data types can be edited i.e., they can change at runtime. Eg
– List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at
runtime. Eg – String, Tuple, etc.
18. What is a Variable Scope in Python?
The location where we can find a variable and also access it if required
is called the scope of a variable.
Python Local variable: Local variables are those that are initialized
within a function and are unique to that function. A local variable
cannot be accessed outside of the function.
Python Global variables: Global variables are the ones that are
defined and declared outside any function and are not specified to
any function.
Module-level scope: It refers to the global objects of the current
module accessible in the program.
Outermost scope: It refers to any built-in names that the program
can call. The name referenced is located last among the objects in
this scope.
19. How is a dictionary different from a list?
[Link] 10/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
A list is an ordered collection of items accessed by their index, while a
dictionary is an unordered collection of key-value pairs accessed using
unique keys. Lists are ideal for sequential data, whereas dictionaries are
better for associative data. For example, a list can store [10, 20, 30],
whereas a dictionary can store {"a": 10, "b": 20, "c": 30}.
20. What is docstring in Python?
Python documentation strings (or docstrings) provide a convenient way
of associating documentation with Python modules, functions, classes
and methods.
Declaring Docstrings: The docstrings are declared using ”’triple
single quotes”’ or “””triple double quotes””” just below the class,
method, or function declaration. All functions should have a
docstring.
Accessing Docstrings: The docstrings can be accessed using the
__doc__ method of the object or using the help function.
21. How is Exceptional handling done in Python?
There are 3 main keywords i.e. try, except and finally which are used to
catch exceptions:
try: A block of code that is monitored for errors.
except: Executes when an error occurs in the try block.
finally: Executes after the try and except blocks, regardless of
whether an error occurred. It’s used for cleanup tasks.
Example: Trying to divide a number by zero will cause an exception.
1 n = 10
2 try:
3 res = n / 0 # This will raise a ZeroDivisionError
4
5 except ZeroDivisionError:
6 print("Can't be divided by zero!")
Output
[Link] 11/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Can't be divided by zero!
Explanation: In this example, dividing number by 0 raises
a ZeroDivisionError. The try block contains the code that might cause
an exception and the except block handles the exception, printing an
error message instead of stopping the program.
1/3
22. What is the difference between Python Arrays and Lists?
Arrays (when talking about the array module in Python) are
specifically used to store a collection of numeric elements that are all
of the same type. This makes them more efficient for storing large
amounts of data and performing numerical computations where the
type consistency is maintained.
Syntax: Need to import the array module to use arrays.
Example:
1 from array import array
2 arr = array('i', [1, 2, 3, 4]) # Array of integers
Lists are more flexible than arrays in that they can hold elements of
different types (integers, strings, objects, etc.). They come built-in
with Python and do not require importing any additional modules.
Lists support a variety of operations that can modify the list.
Example:
[Link] 12/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
1 a = [1, 'hello', 3.14, [1, 2, 3]]
read more about Difference between List and Array in Python
23. What are Modules and Packages in Python?
A module is a single file that contains Python code (functions, variables,
classes) which can be reused in other programs. You can think of it as a
code library. For example: math is a built-in module that provides math
functions like sqrt(), pi, etc.
1 import math
2 print([Link](16))
package is a collection of related modules stored in a directory. It helps
in organizing and grouping modules together for easier management.
For example: The numpy package contains multiple modules for
numerical operations.
To create a package, the directory must contain a special file named
__init__.py.
Intermediate Python Interview Questions
24. What is the difference between xrange and range functions?
range() and xrange() are two functions that could be used to iterate a
certain number of times in for loops in Python.
In Python 3, there is no xrange, but the range function behaves like
xrange.
In Python 2
range() – This returns a range object, which is an immutable
sequence type that generates the numbers on demand.
xrange() – This function returns the generator object that
can be used to display numbers only by looping. The only
particular range is displayed on demand and hence called
lazy evaluation.
[Link] 13/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
25. What is Dictionary Comprehension? Give an Example
Dictionary Comprehension is a syntax construction to ease the creation
of a dictionary based on the existing iterable.
1 keys = ['a','b','c','d','e']
2 values = [1,2,3,4,5]
3
4 # this line shows dict comprehension here
5 d = { k:v for (k,v) in zip(keys, values)}
6
7 # We can use below too
8 # d = dict(zip(keys, values))
9
10 print (d)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
26. Is Tuple Comprehension possible in Python? If yes, how and
if not why?
Tuple comprehensions are not directly supported, Python's existing
features like generator expressions and the tuple() function provide
flexible alternatives for creating tuples from iterable data.
(i for i in (1, 2, 3))
Tuple comprehension is not possible in Python because it will end up in
a generator, not a tuple comprehension.
27. Differentiate between List and Tuple?
Let’s analyze the differences between List and Tuple:
List
Lists are Mutable datatype.
Lists consume more memory
[Link] 14/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
The list is better for performing operations, such as insertion and
deletion.
The implication of iterations is Time-consuming
Tuple
Tuples are Immutable datatype.
Tuple consumes less memory as compared to the list
A Tuple data type is appropriate for accessing the elements
The implication of iterations is comparatively Faster
28. What is the difference between a shallow copy and a deep
copy?
Below is the tabular Difference between the Shallow Copy and Deep
Copy:
Shallow Copy Deep Copy
Shallow Copy stores the
Deep copy stores copies of the
references of objects to the
object’s value.
original memory address.
Shallow Copy reflects changes Deep copy doesn’t reflect changes
made to the new/copied object in made to the new/copied object in
the original object. the original object.
Shallow Copy stores the copy of Deep copy stores the copy of the
the original object and points the original object and recursively
references to the objects. copies the objects as well.
A shallow copy is faster. Deep copy is comparatively slower.
29. Which sorting technique is used by sort() and sorted()
functions of python?
[Link] 15/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Python uses the Tim Sort algorithm for sorting. It’s a stable sorting
whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived
from merge sort and insertion sort, designed to perform well on many
kinds of real-world data.
30. What are Decorators?
Decorators are a powerful and flexible way to modify or extend the
behavior of functions or methods, without changing their actual code. A
decorator is essentially a function that takes another function as an
argument and returns a new function with enhanced functionality.
Decorators are often used in scenarios such as logging, authentication
and memorization, allowing us to add additional functionality to existing
functions or methods in a clean, reusable way.
31. How do you debug a Python program?
1. Using pdb (Python Debugger):
pdb is a built-in module that allows you to set breakpoints and step
through the code line by line. You can start the debugger by adding
import pdb; pdb.set_trace() in your code where you want to begin
debugging.
1 import pdb
2 x = 5
3 pdb.set_trace() # Debugger starts here
4 print(x)
Output
> /home/repl/02c07243-5df9-4fb0-a2cd-
54fe6d597c80/[Link](4)<module>()
-> print(x)
(Pdb)
2. Using logging Module:
For more advanced debugging, the logging module provides a flexible
way to log messages with different severity levels (INFO, DEBUG,
[Link] 16/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
WARNING, ERROR, CRITICAL).
1 import logging
2 [Link](level=[Link])
3 [Link]("This is a debug message")
Output
DEBUG:root:This is a debug message
32. What are Iterators in Python?
In Python, iterators are used to iterate a group of elements, containers
like a list. Iterators are collections of items and they can be a list, tuples,
or a dictionary. Python iterator implements __itr__ and the next()
method to iterate the stored elements. We generally use loops to iterate
over the collections (list, tuple) in Python.
33. What are Generators in Python?
In Python, the generator is a way that specifies how to implement
iterators. It is a normal function except that it yields expression in the
function. It does not implement __itr__ and __next__ method and
reduces other overheads as well.
If a function contains at least a yield statement, it becomes a generator.
The yield keyword pauses the current execution by saving its states and
then resumes from the same when required.
34. Does Python supports multiple Inheritance?
When a class is derived from more than one base class it is called
multiple Inheritance. The derived class inherits all the features of the
base case.
[Link] 17/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Multiple Inheritance
Python does support multiple inheritances, unlike Java.
35. What is Polymorphism in Python?
Polymorphism means the ability to take multiple forms. Polymorphism
allows different classes to be treated as if they are instances of the
same class through a common interface. This means that a method in a
parent class can be overridden by a method with the same name in a
child class, but the child class can provide its own specific
implementation. This allows the same method to operate differently
depending on the object that invokes it. Polymorphism is about
overriding, not overloading; it enables methods to operate on objects of
different classes, which can have their own attributes and methods,
providing flexibility and reusability in the code.
36. Define encapsulation in Python?
Encapsulation is the process of hiding the internal state of an object and
requiring all interactions to be performed through an object’s methods.
This approach:
Provides better control over data.
Prevents accidental modification of data.
Promotes modular programming.
[Link] 18/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Python achieves encapsulation
through public, protected and private attributes.
Encapsulation in Python
37. How do you do data abstraction in Python?
Data Abstraction is providing only the required details and hides the
implementation from the world. The focus is on exposing only the
essential features and hiding the complex implementation behind an
interface. It can be achieved in Python by using interfaces and abstract
classes.
38. How is memory management done in Python?
Python uses its private heap space to manage the memory. Basically, all
the objects and data structures are stored in the private heap space.
Even the programmer can not access this private space as the
interpreter takes care of this space. Python also has an inbuilt garbage
collector, which recycles all the unused memory and frees the memory
and makes it available to the heap space.
39. How to delete a file using Python?
We can delete a file using Python by following approaches:
1. Python Delete File using os. remove
2. Delete file in Python using the send2trash module
[Link] 19/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
3. Python Delete File using [Link]
40. What is slicing in Python?
Python Slicing is a string operation for extracting a part of the string, or
some part of a list. With this operator, one can specify where to start
the slicing, where to end and specify the step. List slicing returns a new
list from the existing list.
Syntax:
substring = s[start : end : step]
41. What is a namespace in Python?
A namespace in Python refers to a container where names (variables,
functions, objects) are mapped to objects. In simple terms, a namespace
is a space where names are defined and stored and it helps avoid
naming conflicts by ensuring that names are unique within a given
scope.
Types of namespaces
Types of Namespaces:
1. Built-in Namespace: Contains all the built-in functions and
exceptions, like print(), int(), etc. These are available in every Python
program.
2. Global Namespace: Contains names from all the objects, functions
and variables in the program at the top level.
[Link] 20/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
3. Local Namespace: Refers to names inside a function or method. Each
function call creates a new local namespace.
Python Interview
Advanced Python Interview Questions & Answers
42. What is PIP?
PIP is an acronym for Python Installer Package which provides a
seamless interface to install various Python modules. It is a command-
line tool that can search for packages over the internet and install them
without any user interaction.
43. What is a zip function?
Python zip() function returns a zip object, which maps a similar index of
multiple containers. It takes an iterable, converts it into an iterator and
aggregates the elements based on iterables passed. It returns an
iterator of tuples.
Syntax:
zip(*iterables)
44. What are Pickling and Unpickling?
Pickling: The pickle module converts any Python object into a byte
stream (not a string representation). This byte stream can then be
[Link] 21/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
stored in a file, sent over a network, or saved for later use. The
function used for pickling is [Link]().
Unpickling: The process of retrieving the original Python object from
the byte stream (saved during pickling) is called unpickling. The
function used for unpickling is [Link]().
45. What is the difference between @classmethod,
@staticmethod and instance methods in Python?
1. Instance Method operates on an instance of the class and has access
to instance attributes and takes self as the first parameter. Example:
def method(self):
2. Class Method directly operates on the class itself and not on
instance, it takes cls as the first parameter and defined with
@classmethod.
Example: @classmethod def method(cls):
3. Static Method does not operate on an instance or the class and takes
no self or cls as an argument and is defined with @staticmethod.
Example: @staticmethod def method(): align it and dont bolod
anything and not bullet points
46. What is __init__() in Python and how does self play a role in
it?
__init__() is Python's equivalent of constructors in OOP, called
automatically when a new object is created. It initializes the object's
attributes with values but doesn’t handle memory allocation.
Memory allocation is handled by the __new__() method, which is
called before __init__().
The self parameter in __init__() refers to the instance of the class,
allowing access to its attributes and methods.
[Link] 22/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
self must be the first parameter in all instance methods, including
__init__()
1 class MyClass:
2 def __init__(self, value):
3 [Link] = value # Initialize object attribute
4
5 def display(self):
6 print(f"Value: {[Link]}")
7
8 obj = MyClass(10)
9 [Link]()
Output
Value: 10
47. Write a code to display the current time?
1 import time
2
3 currenttime= [Link]([Link]())
4 print ("Current time is", currenttime)
48. What are Access Specifiers in Python?
Python uses the ‘_’ symbol to determine the access control for a specific
data member or a member function of a class. A Class in Python has
three types of Python access modifiers:
Public Access Modifier: The members of a class that are declared
public are easily accessible from any part of the program. All data
members and member functions of a class are public by default.
Protected Access Modifier: The members of a class that are
declared protected are only accessible to a class derived from it. All
data members of a class are declared protected by adding a single
underscore '_' symbol before the data members of that class.
[Link] 23/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
Private Access Modifier: The members of a class that are declared
private are accessible within the class only, the private access
modifier is the most secure access modifier. Data members of a class
are declared private by adding a double underscore ‘__’ symbol
before the data member of that class.
49. What are unit tests in Python?
Unit Testing is the first level of software testing where the smallest
testable parts of the software are tested. This is used to validate that
each unit of the software performs as designed. The unit test framework
is Python’s xUnit style framework. The White Box Testing method is
used for Unit testing.
50. Python Global Interpreter Lock (GIL)?
Python Global Interpreter Lock (GIL) is a type of process lock that is
used by Python whenever it deals with processes. Generally, Python
only uses only one thread to execute the set of written statements. The
performance of the single-threaded process and the multi-threaded
process will be the same in Python and this is because of GIL in Python.
We can not achieve multithreading in Python because we have a global
interpreter lock that restricts the threads and works as a single thread.
51. What are Function Annotations in Python?
Function Annotation is a feature that allows you to add metadata to
function parameters and return values. This way you can specify the
input type of the function parameters and the return type of the
value the function returns.
Function annotations are arbitrary Python expressions that are
associated with various parts of functions. These expressions are
evaluated at compile time and have no life in Python’s runtime
environment. Python does not attach any meaning to these
annotations. They take life when interpreted by third-party libraries,
for example, mypy.
[Link] 24/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
52. What are Exception Groups in Python?
The latest feature of Python 3.11, Exception Groups. The
ExceptionGroup can be handled using a new except* syntax. The *
symbol indicates that multiple exceptions can be handled by each
except* clause.
ExceptionGroup is a collection/group of different kinds of Exception.
Without creating Multiple Exceptions we can group together different
Exceptions which we can later fetch one by one whenever necessary,
the order in which the Exceptions are stored in the Exception Group
doesn’t matter while calling them.
try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...
53. What is Python Switch Statement?
From version 3.10 upward, Python has implemented a switch case
feature called “structural pattern matching”. You can implement this
feature with the match and case keywords. Note that the underscore
symbol is what you use to define a default case for the switch
statement in Python.
Note: Before Python 3.10 Python doesn't support match Statements.
match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
[Link] 25/30
5/26/25, 9:16 AM Python Interview Questions and Answers | GeeksforGeeks
action-3
case _:
action-default
54. What is Walrus Operator?
Walrus Operator allows you to assign a value to a variable within an
expression. This can be useful when you need to use a value multiple
times in a loop, but don't want to repeat the calculation.
Walrus Operator is represented by the `:=` syntax and can be used in
a variety of contexts including while loops and if statements.
Note: Python versions before 3.8 doesn't support Walrus Operator.
1 numbers = [1, 2, 3, 4, 5]
2
3 while (n := len(numbers)) > 0:
4 print([Link]())
Output
5
4
3
2
1
Comment More info
Campus Training Program
Similar Reads
NumPy Interview Questions with Answers
If you are aware of Python, then you are also aware of NumPy because it
is one of the most commonly used libraries in Python for working with…
[Link] 26/30
1. What is a database?
Answer:
A database is an organized collection of data that allows users to store, retrieve, and manage
information efficiently. It helps in organizing data in a structured manner so that it can be
easily accessed and manipulated.
Example:
• A school database stores student details, course enrollments, and exam scores.
• A bank database stores customer details, transactions, and account balances.
Types of databases:
1. Relational Database (RDBMS) – Stores data in tables (e.g., MySQL, PostgreSQL).
2. NoSQL Database – Stores data in key-value, document, or graph format (e.g.,
MongoDB, Cassandra).
2. What is DBMS and RDBMS?
Answer:
A DBMS (Database Management System) is software that allows users to store, retrieve,
and manage data. It does not support relationships between tables.
An RDBMS (Relational Database Management System) is an advanced DBMS that stores
data in tables with relationships using primary and foreign keys.
Feature DBMS RDBMS
Data Storage Stores data as files Stores data in tables
Relationships No relationships Relationships using keys
Example MS Access, FileMaker MySQL, SQL Server, Oracle
3. What is Normalization?
Answer:
Normalization is the process of organizing a database to reduce redundancy and improve
efficiency. It divides a large table into smaller related tables to ensure data consistency.
Benefits:
✔Reduces data duplication
✔ Improves data integrity
✔ Simplifies database maintenance
Example:
A table with student details:
Student_ID Name Course Instructor
101 John Math Mr. Smith
102 Alice Science Mr. Brown
After normalization:
Student Table:
Student_ID Name
101 John
102 Alice
Course Table:
Course_ID Course Instructor
1 Math Mr. Smith
2 Science Mr. Brown
Now, data is stored efficiently without duplication.
4. Explain BCNF (Boyce-Codd Normal Form)?
Answer:
BCNF is a stronger version of the Third Normal Form (3NF) that ensures a table is divided
into smaller tables to avoid redundancy.
BCNF Rule:
A table is in BCNF if every functional dependency (A → B) has A as a super key (a unique
identifier).
Example:
Student_ID Course Instructor
101 Math Mr. Smith
102 Science Mr. Brown
Since Instructor depends on Course and not Student_ID, we separate the tables into:
Student Table:
Student_ID Course
101 Math
102 Science
Instructor Table:
Course Instructor
Math Mr. Smith
Science Mr. Brown
Now, the tables are in BCNF as dependencies are correctly organized.
5. What are Joins? Explain their types.
Answer:
Joins allow combining data from two or more tables based on a related column.
Types of Joins:
1. INNER JOIN – Returns only matching records from both tables.
SQL
SELECT [Link], department.dept_name
FROM employees
INNER JOIN department ON employees.dept_id = [Link];
2. LEFT JOIN – Returns all records from the left table and matching records from the
right table.
3. RIGHT JOIN – Returns all records from the right table and matching records from
the left table.
4. FULL JOIN – Returns all records from both tables, filling unmatched data with
NULL.
5. CROSS JOIN – Returns the Cartesian product (all possible combinations of rows).
6. SELF JOIN – A table joins with itself.
6. What is an Index?
Answer:
An index is a special data structure that improves query performance by making searches
faster. It works like a book index, allowing the database to find records without scanning the
entire table.
Example:
If we search for a student by ID, an index allows quick lookup instead of checking each row.
SQL
CREATE INDEX student_index ON students(student_id);
Types of Indexes:
✔ Primary Index – Created automatically on primary key.
✔ Unique Index – Ensures no duplicate values.
✔ Composite Index – Created on multiple columns.
7. What is Savepoint and Commit?
Answer:
• COMMIT permanently saves changes in the database.
• SAVEPOINT allows setting a point in a transaction to roll back changes if needed.
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
SAVEPOINT checkpoint1;
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;
ROLLBACK TO checkpoint1;
COMMIT;
8. What is DDL?
Answer:
DDL (Data Definition Language) is used to define and manage database structures.
Command Purpose
CREATE Creates a table or database
ALTER Modifies a table
DROP Deletes a table or database
CREATE TABLE students (id INT, name VARCHAR(50));
9. What is DCL?
Answer:
DCL (Data Control Language) is used for granting or revoking access to users.
Command Purpose
GRANT Gives user access
REVOKE Removes user access
GRANT SELECT ON students TO user1;
10. What are Procedures and Stored Procedures?
Answer:
A procedure is a set of SQL statements stored in the database that can be executed multiple
times.
CREATE PROCEDURE get_students() AS
BEGIN
SELECT * FROM students;
END;
Benefits:
✔ Improves performance
✔ Reduces redundant code
11. What are Functions?
Answer:
A function is similar to a procedure but returns a value.
CREATE FUNCTION get_total_salary() RETURNS INT AS
BEGIN
RETURN (SELECT SUM(salary) FROM employees);
END;
12. What are Views?
Answer:
A view is a virtual table based on a query. It does not store data but simplifies complex
queries.
CREATE VIEW employee_info AS
SELECT name, department FROM employees;
13. Difference between TRUNCATE and DELETE?
Answer:
Feature TRUNCATE DELETE
Type DDL (Data Definition Language) DML (Data Manipulation Language)
Removes All rows from a table Specific rows based on condition
WHERE Clause Not allowed Allowed
Feature TRUNCATE DELETE
Rollback Cannot be rolled back Can be rolled back if inside a transaction
Speed Faster Slower due to logging
Example:
• DELETE (removes specific records and can be rolled back)
DELETE FROM employees WHERE id = 1;
• TRUNCATE (removes all records permanently)
TRUNCATE TABLE employees;
14. SQL command to INSERT data into a table.
Answer:
#The INSERT command adds new records into a table.
INSERT INTO employees (id, name, salary)
VALUES (1, 'John Doe', 50000);
#To insert multiple records:
INSERT INTO employees (id, name, salary)
VALUES
(2, 'Alice', 60000), (3, 'Bob', 70000);
15. SQL query to UPDATE data in a table.
Answer:
#The UPDATE statement modifies existing records in a table.
UPDATE employees
SET salary = 65000
WHERE id = 1;
#Updating multiple fields:
UPDATE employees
SET salary = 70000, department = 'HR'
WHERE id = 2;
16. SQL command to DELETE and DROP a table.
Answer:
• DELETE removes specific rows but keeps the table structure.
DELETE FROM employees WHERE id = 1;
• DROP removes the entire table, including structure.
DROP TABLE employees;
17. DROP, DELETE, and UPDATE query with condition.
Answer:
• DELETE with condition (removes specific rows)
DELETE FROM employees WHERE department = 'Sales';
• UPDATE with condition (modifies specific records)
UPDATE employees SET salary = salary + 5000 WHERE department = 'IT';
• DROP (removes table completely)
DROP TABLE employees;
18. SQL command for INNER JOIN.
Answer:
INNER JOIN returns only matching rows from both tables.
SELECT [Link], department.dept_name
FROM employees
INNER JOIN department ON employees.dept_id = [Link];
19. Print the top 10 values in a table.
Answer:
To fetch the top 10 rows from a table:
• For MySQL & PostgreSQL:
SELECT * FROM employees LIMIT 10;
• For SQL Server:
SELECT TOP 10 * FROM employees;
20. Query to update an employee's salary.
Answer:
UPDATE employees SET salary = salary + 5000 WHERE id = 3;
This increases the salary of employee with id = 3 by 5000.
21. Query to update the location of an employee.
Answer:
UPDATE employees
SET location = 'New York'
WHERE id = 2;
This updates the location of employee with id = 2.
22. Query to sum employee salaries.
Answer:
To get the total salary of all employees:
SELECT SUM(salary) FROM employees;
To find total salary department-wise:
SELECT department, SUM(salary) FROM employees
GROUP BY department;
23. Difference between CHAR, VARCHAR, and VARCHAR2?
Answer:
Type Definition Storage
CHAR(n) Fixed-length string Always takes n bytes
VARCHAR(n) Variable-length string Takes only required space
Oracle-specific optimized version of Same as VARCHAR but stores
VARCHAR2(n)
VARCHAR NULL efficiently
Example:
CREATE TABLE test (
col1 CHAR(10),
col2 VARCHAR(10),
col3 VARCHAR2(10)
);
24. List of DBMS Software.
Answer:
Examples of DBMS software (non-relational databases):
• MS Access
• FoxPro
• FileMaker
• SQLite
These systems do not enforce relationships between tables strictly.
25. List of RDBMS Software.
Answer:
Examples of RDBMS software (relational databases):
• MySQL
• PostgreSQL
• SQL Server
• Oracle Database
• IBM Db2
These systems store data in tables and enforce relationships using keys
1. What are the different types of SQL commands?
Answer:
SQL commands are divided into five types:
1. DDL (Data Definition Language) – Defines database structure.
o Commands: CREATE, ALTER, DROP, TRUNCATE
2. DML (Data Manipulation Language) – Modifies data in tables.
o Commands: INSERT, UPDATE, DELETE
3. DCL (Data Control Language) – Controls access to data.
o Commands: GRANT, REVOKE
4. TCL (Transaction Control Language) – Manages transactions.
o Commands: COMMIT, ROLLBACK, SAVEPOINT
5. DQL (Data Query Language) – Retrieves data from a database.
o Command: SELECT
2. What is the difference between SQL and MySQL?
Answer:
• SQL (Structured Query Language) is a language used to manage and query
databases.
• MySQL is a database management system (RDBMS) that uses SQL to store and
retrieve data.
Feature SQL MySQL
Type Language Database software
Purpose Query databases Manage relational databases
Example SELECT * FROM students; MySQL is software like Oracle, SQL Server
3. What is the difference between a Primary Key and a Unique Key?
Answer:
• Primary Key uniquely identifies each record in a table and cannot have NULL
values.
• Unique Key also ensures uniqueness, but it can have one NULL value.
Feature Primary Key Unique Key
Uniqueness Ensures unique values Ensures unique values
NULL Values Not allowed Allowed (one NULL)
Number of Keys Only one per table Multiple per table
Example:
CREATE TABLE students (
id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
4. What is the difference between a Primary Key and a Foreign Key?
Answer:
• Primary Key uniquely identifies records in a table.
• Foreign Key links a column in one table to the Primary Key in another table.
Feature Primary Key Foreign Key
Purpose Uniquely identifies a record Establishes a relationship
Uniqueness Always unique Can have duplicate values
NULL Allowed? No Yes
Example:
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE courses (
course_id INT PRIMARY KEY,
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
);
5. What is a Candidate Key?
Answer:
A Candidate Key is a column (or set of columns) that can uniquely identify a record. A
table can have multiple Candidate Keys, but only one is chosen as the Primary Key.
Example:
Student_ID Email Phone Name
101 a@[Link] 9876543210 John
102 b@[Link] 9123456789 Alice
Here, Student_ID, Email, and Phone can uniquely identify each student, so they are
Candidate Keys. If we choose Student_ID as the Primary Key, then the others remain
Unique Keys.
6. What is the difference between WHERE and HAVING clause?
Answer:
• WHERE filters data before grouping.
• HAVING filters data after grouping (used with GROUP BY).
Clause Used for Works with
WHERE Filtering rows before grouping SELECT, UPDATE, DELETE
HAVING Filtering groups after GROUP BY GROUP BY
Example:
Sql
-- Using WHERE
SELECT * FROM employees WHERE salary > 50000;
-- Using HAVING
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
7. What is the difference between GROUP BY and ORDER BY?
Answer:
• GROUP BY groups rows with the same values.
• ORDER BY sorts the rows.
Clause Purpose Works with
GROUP Aggregation functions (SUM,
Groups rows based on a column
BY COUNT)
ORDER Sorts rows in ascending/descending
Any column
BY order
Example:
-- Using GROUP BY
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
-- Using ORDER BY
SELECT * FROM employees ORDER BY salary DESC;
8. What is a Constraint in SQL? Name different types of constraints.
Answer:
A constraint ensures data integrity in a table.
Types of Constraints:
1. PRIMARY KEY – Ensures unique and non-null values.
2. FOREIGN KEY – Establishes a link between tables.
3. UNIQUE – Ensures uniqueness.
4. NOT NULL – Prevents NULL values.
5. CHECK – Sets a condition for values.
6. DEFAULT – Assigns a default value if none is given.
Example:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
salary INT CHECK (salary > 30000),
department_id INT FOREIGN KEY REFERENCES departments(id)
);
9. What is an Alias in SQL?
Answer:
An Alias is a temporary name for a table or column to improve readability.
Example:
SELECT name AS EmployeeName, salary AS MonthlySalary FROM employees;
Here, name is renamed as EmployeeName, and salary is renamed as MonthlySalary.
Aliases are helpful in complex queries and do not affect the actual database structure.
1. What are Aggregate Functions in SQL? Explain with examples.
Answer:
Aggregate functions perform calculations on multiple rows and return a single result.
Common Aggregate Functions:
1. COUNT() – Counts the number of rows.
2. SUM() – Returns the total sum of a column.
3. AVG() – Returns the average value.
4. MIN() – Returns the smallest value.
5. MAX() – Returns the largest value.
Example:
SELECT COUNT(*) FROM employees; -- Counts total employees
SELECT SUM(salary) FROM employees; -- Total salary of all employees
SELECT AVG(salary) FROM employees; -- Average salary
SELECT MIN(salary) FROM employees; -- Lowest salary
SELECT MAX(salary) FROM employees; -- Highest salary
2. What is the difference between COUNT(), SUM(), AVG(), MIN(), and MAX()?
Answer:
Function Purpose
COUNT() Counts total rows
SUM() Adds values of a numeric column
AVG() Calculates average value
MIN() Finds smallest value
MAX() Finds largest value
SELECT COUNT(*) FROM employees; -- Total employees
SELECT SUM(salary) FROM employees; -- Total salary
SELECT AVG(salary) FROM employees; -- Average salary
SELECT MIN(salary) FROM employees; -- Minimum salary
SELECT MAX(salary) FROM employees; -- Maximum salary
3. What is a Subquery? Explain types of subqueries with examples.
Answer:
A subquery is a query inside another query.
Types of Subqueries:
1. Single-row Subquery – Returns one value
2. Multi-row Subquery – Returns multiple values
3. Correlated Subquery – Depends on the outer query
Example:
-- Single-row Subquery
SELECT name, salary FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
-- Multi-row Subquery
SELECT name FROM employees
WHERE department_id IN (SELECT id FROM departments WHERE location = 'New
York');
4. What is a Correlated Subquery? How is it different from a normal subquery?
Answer:
A correlated subquery depends on the outer query. It executes once for each row of the
outer query.
Example:
SELECT name, salary
FROM employees e1
WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e1.department_id =
e2.department_id);
This finds employees who earn more than the average salary in their department.
Difference from a Normal Subquery:
• A normal subquery runs once and gives a result to the outer query.
• A correlated subquery runs multiple times (once for each row in the outer query).
5. What is a Self Join? Give an example.
Answer:
A self join joins a table with itself.
Example:
SELECT [Link] AS Employee, [Link] AS Manager
FROM employees e1
JOIN employees e2
ON e1.manager_id = [Link];
This query finds employees and their managers from the same table.
6. What is the difference between Cross Join and Full Outer Join?
Answer:
Feature Cross Join Full Outer Join
Returns all matching & non-
Purpose Combines all rows from both tables
matching rows
Matching No condition (produces Cartesian
Uses a condition
Condition product)
No NULLs (unless table has Returns NULL for non-matching
NULL Values
NULLs) rows
Example:
-- Cross Join
SELECT * FROM employees CROSS JOIN departments;
-- Full Outer Join
SELECT * FROM employees
FULL OUTER JOIN departments
ON employees.department_id = [Link];
7. What are Common Table Expressions (CTE) in SQL?
Answer:
A CTE (Common Table Expression) is a temporary result set that improves query
readability.
Example:
WITH EmployeeSalary AS (
SELECT name, salary FROM employees WHERE salary > 50000
)
SELECT * FROM EmployeeSalary;
Here, EmployeeSalary is a temporary result set that stores employees earning more than
50,000.
8. What is a Window Function in SQL?
Answer:
A Window Function performs calculations across a group of rows related to the current
row without grouping them.
Example:
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS Rank
FROM employees;
This ranks employees based on salary without grouping them.
9. What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?
Answer:
Function Purpose
RANK() Assigns a rank, but skips numbers when there are duplicates
DENSE_RANK() Assigns a rank, but does not skip numbers
ROW_NUMBER() Assigns a unique number to each row
Example:
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS Rank,
DENSE_RANK() OVER (ORDER BY salary DESC) AS DenseRank,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS RowNum
FROM employees;
10. How do you find duplicate records in a table?
Answer:
SELECT name, COUNT(*)
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;
This finds names that appear more than once.
11. How do you remove duplicate records from a table?
Answer:
DELETE FROM employees
WHERE id NOT IN (
SELECT MIN(id) FROM employees GROUP BY name
);
This keeps only the first record and deletes duplicates.
12. Write an SQL query to find the second highest salary.
Answer:
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
This finds the second highest salary by selecting the maximum salary that is less than the
highest salary.
13. Write an SQL query to retrieve duplicate records from a table.
Answer:
SELECT name, COUNT(*)
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;
This retrieves employees who appear more than once.
14. Write an SQL query to find the employees who earn more than their manager.
Answer:
SELECT [Link] AS Employee, [Link], [Link] AS Manager, [Link] AS
ManagerSalary
FROM employees e1
JOIN employees e2 ON e1.manager_id = [Link]
WHERE [Link] > [Link];
This finds employees whose salary is higher than their manager's salary.
1. What are the advantages of using Indexes in SQL?
Answer:
An index improves query performance by allowing faster searches in a table.
Advantages:
1. Speeds up searches – Finding rows is much faster.
2. Improves sorting – Queries using ORDER BY work efficiently.
3. Faster joins – Speeds up queries that use JOIN.
4. Reduces disk I/O – Less data is scanned for each query.
Example:
CREATE INDEX idx_employee_name ON employees(name);
Now, searches for employees by name will be faster.
2. What is the difference between Clustered and Non-Clustered Index?
Answer:
Feature Clustered Index Non-Clustered Index
Storage Physically rearranges data Stores index separately
Number per
Only one per table Multiple allowed
Table
Faster for retrieving ranges Slower for range queries but good for
Speed
of data random lookups
Example Primary Key Index Index on name column
Example:
-- Clustered Index (automatically created on Primary Key)
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50)
);
-- Non-Clustered Index
CREATE INDEX idx_employee_name ON employees(name);
3. What is SQL Injection? How can it be prevented?
Answer:
SQL Injection is an attack where hackers insert malicious SQL code into queries.
Example of SQL Injection Attack:
SELECT * FROM users WHERE username = 'admin' OR 1=1;
Here, 1=1 makes the query return all users instead of just "admin".
How to Prevent SQL Injection?
1. Use Prepared Statements
SELECT * FROM users WHERE username = ? AND password = ?;
2. Use Stored Procedures
CREATE PROCEDURE GetUser(IN user_name VARCHAR(50))
BEGIN
SELECT * FROM users WHERE username = user_name;
END;
3. Escape User Input – Validate and sanitize input data.
4. What is the difference between OLTP and OLAP?
Answer:
OLTP (Online Transaction OLAP (Online Analytical
Feature
Processing) Processing)
Purpose Handles transactions Handles reporting & analysis
Operations Insert, Update, Delete Read-heavy (queries, reports)
Data
Small, frequent transactions Large datasets
Volume
Example Banking, e-commerce Data Warehouses, BI Tools
Example Queries:
• OLTP: UPDATE accounts SET balance = balance - 500 WHERE account_id = 123;
• OLAP: SELECT department, SUM(salary) FROM employees GROUP BY
department;
5. What is Denormalization? When should it be used?
Answer:
Denormalization reduces joins by adding redundant data, improving performance in read-
heavy applications.
When to use it?
1. When queries are slow due to multiple joins.
2. For read-heavy systems like OLAP or reporting databases.
Example:
Instead of two tables (orders and customers), denormalization stores customer details inside
orders:
SELECT order_id, customer_name, customer_address FROM orders;
This avoids a JOIN with the customers table, making the query faster.
6. How can you improve the performance of an SQL query?
Answer:
1. Use Indexes – Speeds up searches.
2. Avoid SELECT * – Fetch only needed columns.
3. Use Joins Efficiently – Prefer INNER JOIN over OUTER JOIN.
4. Use EXISTS instead of IN – Faster when checking for values.
5. Partition Large Tables – Helps in handling large datasets.
6. Optimize WHERE Clause – Use indexed columns in WHERE conditions.
7. Avoid Functions in WHERE Clause – Functions slow down queries.
*Example (Avoiding SELECT):
-- Bad
SELECT * FROM employees;
-- Good
SELECT id, name, salary FROM employees;
7. What is Query Optimization? What are some best practices?
Answer:
Query Optimization improves SQL query performance by reducing execution time and
resource usage.
Best Practices:
1. Analyze Execution Plan (EXPLAIN) – Understand query performance.
2. Use Proper Indexing – Add indexes on frequently used columns.
3. Use Joins Smartly – Avoid unnecessary joins.
4. Limit Result Sets – Use LIMIT for large queries.
5. Use Caching – Store frequently used data in cache.
6. Avoid Subqueries – Use JOIN instead of correlated subqueries.
Example (Using EXPLAIN to check query plan):
EXPLAIN SELECT * FROM employees WHERE salary > 50000;
This shows whether the query is using indexes properly.
8. What are Partitioned Tables? How do they improve performance?
Answer:
Partitioning divides a large table into smaller parts to improve performance.
Types of Partitioning:
1. Range Partitioning – Divides based on a range of values (e.g., date ranges).
2. List Partitioning – Divides based on specific values.
3. Hash Partitioning – Uses a hash function to split data.
Example (Range Partitioning on a Date Column):
CREATE TABLE orders (
order_id INT,
order_date DATE
) PARTITION BY RANGE(order_date) (
PARTITION p1 VALUES LESS THAN ('2024-01-01'),
PARTITION p2 VALUES LESS THAN ('2025-01-01')
);
Now, queries on recent orders run faster.
9. What is the difference between EXISTS and IN? Which one is faster?
Answer:
Feature EXISTS IN
Works on Subqueries Lists of values
Speed Faster for large data sets Slower for large lists
Example EXISTS (SELECT 1 FROM employees) IN (SELECT id FROM employees)
Example (Using EXISTS for better performance):
SELECT * FROM employees e
WHERE EXISTS (SELECT 1 FROM departments d WHERE e.department_id = [Link]);
EXISTS stops searching as soon as a match is found, making it faster than IN for large
data sets.
10. How do you monitor database performance in SQL?
Answer:
1. Use EXPLAIN – Analyzes query execution plans.
2. Monitor Slow Queries – Check long-running queries.
3. Use Database Profiler Tools – MySQL Slow Query Log, SQL Server Profiler.
4. Check CPU and Memory Usage – Monitor system performance.
5. Check Index Usage – Ensure queries use indexes.
1. What is a Stored Procedure in SQL?
Answer:
A Stored Procedure is a set of SQL statements stored in the database and executed when
needed. It improves performance and security.
Example:
CREATE PROCEDURE GetAllEmployees()
BEGIN
SELECT * FROM employees;
END;
To execute:
CALL GetAllEmployees();
2. What are the benefits of Stored Procedures?
Answer:
1. Faster Execution – SQL is precompiled.
2. Code Reusability – Write once, use many times.
3. Better Security – Prevents SQL injection.
4. Reduced Network Traffic – Only procedure name is sent, not full SQL.
3. What is the difference between a Stored Procedure and a Function?
Answer:
Feature Stored Procedure Function
Can return multiple Always returns one
Returns Value?
values value
Can use SELECT? Yes Yes
Can use DML (INSERT, UPDATE,
Yes No
DELETE)?
Feature Stored Procedure Function
Can be used in a SELECT statement? No Yes
Example (Function to get Employee Count):
CREATE FUNCTION GetEmployeeCount() RETURNS INT
BEGIN
DECLARE emp_count INT;
SELECT COUNT(*) INTO emp_count FROM employees;
RETURN emp_count;
END;
To execute:
SELECT GetEmployeeCount();
4. What is a Trigger in SQL?
Answer:
A Trigger is an automatic action executed before or after an event like INSERT, UPDATE,
DELETE on a table.
Example (Trigger before inserting data):
CREATE TRIGGER BeforeInsertEmployee
BEFORE INSERT ON employees
FOR EACH ROW
SET NEW.created_at = NOW();
Here, before inserting a new employee, it automatically sets created_at to the current time.
5. What are the types of Triggers?
Answer:
1. BEFORE Trigger – Executes before an action (e.g., BEFORE INSERT).
2. AFTER Trigger – Executes after an action (e.g., AFTER UPDATE).
3. INSTEAD OF Trigger – Used in Views to replace an action.
6. What is the difference between a Trigger and a Stored Procedure?
Answer:
Feature Trigger Stored Procedure
Execution Automatically triggered Manually called
Before/After INSERT, UPDATE, Any operation (SELECT, INSERT,
When Used
DELETE etc.)
Can return
No Yes
values?
7. How to create an AFTER UPDATE Trigger in SQL?
Answer:
CREATE TRIGGER AfterSalaryUpdate
AFTER UPDATE ON employees
FOR EACH ROW
INSERT INTO salary_changes(emp_id, old_salary, new_salary, change_date)
VALUES ([Link], [Link], [Link], NOW());
This trigger stores salary change history after an update.
8. How to disable and enable a Trigger in SQL?
Answer:
Disable Trigger:
ALTER TABLE employees DISABLE TRIGGER AfterSalaryUpdate;
Enable Trigger:
ALTER TABLE employees ENABLE TRIGGER AfterSalaryUpdate;
9. How to execute a Stored Procedure with Parameters?
Answer:
CREATE PROCEDURE GetEmployeeByID(IN emp_id INT)
BEGIN
SELECT * FROM employees WHERE id = emp_id;
END;
To execute:
CALL GetEmployeeByID(101);
10. Can we call a Stored Procedure inside another Stored Procedure?
Answer:
Yes, we can call one stored procedure from another.
Example:
CREATE PROCEDURE GetManagerDetails(IN emp_id INT)
BEGIN
CALL GetEmployeeByID(emp_id);
END;
Here, GetManagerDetails calls GetEmployeeByID.
11. What is a Recursive Stored Procedure?
Answer:
A recursive stored procedure calls itself until a condition is met.
Example (Factorial Calculation):
CREATE PROCEDURE CalculateFactorial(IN num INT, OUT result INT)
BEGIN
IF num = 1 THEN
SET result = 1;
ELSE
CALL CalculateFactorial(num - 1, result);
SET result = result * num;
END IF; END;
To execute:
CALL CalculateFactorial(5, @result);
SELECT @result;
12. Can we use Transactions in a Stored Procedure?
Answer:
Yes, we can use BEGIN, COMMIT, and ROLLBACK in stored procedures.
Example:
CREATE PROCEDURE TransferMoney(IN from_acc INT, IN to_acc INT, IN amount
DECIMAL)
BEGIN
START TRANSACTION;
UPDATE accounts SET balance = balance - amount WHERE id = from_acc;
UPDATE accounts SET balance = balance + amount WHERE id = to_acc;
COMMIT;
END;
If any error occurs, we can use ROLLBACK to undo the changes.
13. How to handle Errors in Stored Procedures?
Answer:
Use DECLARE and HANDLER for error handling.
Example:
CREATE PROCEDURE SafeTransfer(IN from_acc INT, IN to_acc INT, IN amount
DECIMAL)
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET @error = 'Transaction
Failed';
START TRANSACTION;
UPDATE accounts SET balance = balance - amount WHERE id = from_acc;
UPDATE accounts SET balance = balance + amount WHERE id = to_acc;
COMMIT;
END;
If an error occurs, it sets the message instead of stopping execution.
14. How to Drop a Stored Procedure?
Answer:
DROP PROCEDURE IF EXISTS GetEmployeeByID;
This deletes the stored procedure from the database.
15. How to Modify an Existing Stored Procedure?
Answer:
We need to DROP and then CREATE again.
1. Drop the existing procedure:
DROP PROCEDURE GetEmployeeByID;
2. Create a new version:
CREATE PROCEDURE GetEmployeeByID(IN emp_id INT)
BEGIN
SELECT id, name FROM employees WHERE id = emp_id;
END;
16. Can Triggers be used on Views?
Answer:
Yes, but only INSTEAD OF triggers can be used on Views because Views don’t store data.
Example:
CREATE TRIGGER InsteadOfInsertOnView
INSTEAD OF INSERT ON EmployeeView
FOR EACH ROW
INSERT INTO employees (id, name, salary) VALUES ([Link], [Link], [Link]);
17. What is the Maximum Number of Triggers on a Table?
Answer:
Each table can have multiple triggers for different actions (BEFORE, AFTER, etc.), but
databases like MySQL allow only one trigger per event type.
1. What are Transactions in SQL?
Answer:
A transaction is a group of SQL statements that are executed as a single unit. It ensures that
either all operations succeed or none.
Example:
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
If any step fails, the entire transaction is rolled back to keep data consistent.
2. What are ACID properties in SQL?
Answer:
ACID properties ensure safe and reliable transactions.
1. Atomicity – Either all operations succeed or none.
2. Consistency – Ensures database remains valid after a transaction.
3. Isolation – Each transaction runs separately from others.
4. Durability – Changes are saved permanently after COMMIT.
3. What is the difference between COMMIT and ROLLBACK?
Answer:
Feature COMMIT ROLLBACK
Saves changes Undoes all changes since last START
Function
permanently TRANSACTION
Use After successful
When an error occurs
Case transaction
Example:
START TRANSACTION;
UPDATE employees SET salary = salary + 5000 WHERE id = 101;
COMMIT; -- Saves changes
START TRANSACTION;
UPDATE employees SET salary = salary - 5000 WHERE id = 101;
ROLLBACK; -- Undoes changes
4. What is the difference between SAVEPOINT and ROLLBACK?
Answer:
Feature SAVEPOINT ROLLBACK
Function Creates a checkpoint Reverts all changes
Scope Partial rollback (to a point) Full rollback
Example:
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
SAVEPOINT sp1; -- Save progress
UPDATE accounts SET balance = balance - 200 WHERE id = 2;
ROLLBACK TO sp1; -- Undo only the second update
COMMIT;
Here, only the second update is undone, while the first is saved.
5. What are the different types of Locks in SQL?
Answer:
Locks control access to prevent conflicts.
1. Shared Lock – Allows read-only access to multiple users.
2. Exclusive Lock – Prevents others from reading or writing.
3. Row-Level Lock – Locks only one row in a table.
4. Table-Level Lock – Locks the entire table.
5. Deadlock – When two transactions wait for each other to release locks.
6. What is Deadlock in SQL? How can it be avoided?
Answer:
A deadlock occurs when two transactions wait for each other to release locks, and neither
can proceed.
Example:
• Transaction 1 locks Table A and waits for Table B.
• Transaction 2 locks Table B and waits for Table A.
Ways to Avoid Deadlocks:
1. Use consistent order – Always access tables in the same order.
2. Set timeouts – Automatically cancel transactions if they wait too long.
3. Use lower isolation levels – Allows more flexible access.
4. Minimize locking time – Keep transactions short.
7. What is the difference between Pessimistic Locking and Optimistic Locking?
Answer:
Feature Pessimistic Locking Optimistic Locking
Concept Locks data before modifying Locks data only if it changes
Performance Slower (prevents conflicts) Faster (allows concurrency)
Used in High-contention environments Low-contention environments
Example (Optimistic Locking):
UPDATE employees
SET salary = 50000
WHERE id = 101 AND last_updated = '2024-03-10 12:00:00';
Here, the update works only if the data hasn’t changed since the last read.
1. What is a Database Schema?
Answer:
A Database Schema is the structure of a database that defines how data is organized. It
includes:
• Tables (with columns and data types)
• Views
• Indexes
• Stored Procedures
• Triggers
Example:
CREATE SCHEMA EmployeeDB;
This creates a new database schema called EmployeeDB.
2. What is Data Integrity in SQL?
Answer:
Data Integrity ensures that the data in a database is accurate, consistent, and reliable. It is
enforced using:
• Primary Keys (ensure unique rows)
• Foreign Keys (maintain relationships)
• Constraints (like NOT NULL, CHECK, UNIQUE)
Example:
CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
salary DECIMAL(10,2) CHECK (salary > 0)
);
Here, NOT NULL and CHECK help maintain data integrity.
3. What is the difference between Primary Key and Unique Key?
Answer:
Feature Primary Key Unique Key
Purpose Uniquely identifies each row Ensures unique values but allows NULL
NULL Allowed? No Yes (only one NULL)
Number per Table Only 1 Multiple
Index Clustered Index (by default) Non-Clustered Index
Example:
CREATE TABLE Students (
student_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
Here, student_id ensures each row is unique, while email allows unique values but can have
one NULL.
4. What is the difference between a Candidate Key and a Super Key?
Answer:
Feature Candidate Key Super Key
A minimal key that can be a Primary A key that includes additional
Definition
Key columns
Uniqueness Ensures row uniqueness Ensures row uniqueness
Extra
No extra columns May have extra columns
Columns
Example:
• Candidate Keys: { emp_id }, { email } (minimal unique identifiers)
• Super Key: { emp_id, email } (includes extra columns)
From these Candidate Keys, one is chosen as the Primary Key.
5. What is Referential Integrity?
Answer:
Referential Integrity ensures that the relationships between tables remain consistent using
Foreign Keys.
Example:
CREATE TABLE Departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50)
);
CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES Departments(dept_id)
);
• Here, dept_id in Employees must exist in Departments.
• If a department is deleted, we must either prevent deletion or update employees
accordingly.
6. What are Constraints in SQL?
Answer:
Constraints enforce rules to maintain data integrity.
Types of Constraints:
1. PRIMARY KEY – Ensures a unique row.
2. FOREIGN KEY – Maintains relationships between tables.
3. UNIQUE – Ensures unique values in a column.
4. NOT NULL – Prevents NULL values.
5. CHECK – Ensures values meet a condition.
6. DEFAULT – Assigns a default value.
Example:
CREATE TABLE Products (
product_id INT PRIMARY KEY,
price DECIMAL(10,2) CHECK (price > 0),
category VARCHAR(50) DEFAULT 'General'
);
Here,
• CHECK ensures price is always greater than 0.
• DEFAULT assigns "General" if no category is specified.
7. What is a Self-Join and when is it used?
Answer:
A Self-Join is when a table joins with itself. It is used to compare rows within the same
table.
Example (Find employees with the same manager):
SELECT E1.emp_name AS Employee, E2.emp_name AS Manager
FROM Employees E1
JOIN Employees E2 ON E1.manager_id = E2.emp_id;
Here, the Employees table is joined with itself:
• E1 represents employees.
• E2 represents managers.
8. What is a Cross Join in SQL?
Answer:
A Cross Join produces every possible combination of rows from two tables (Cartesian
Product).
Example:
SELECT * FROM Products
CROSS JOIN Categories;
If Products has 5 rows and Categories has 3 rows, the result will have 5 × 3 = 15 rows.
Use Case: When you want all possible pairings of data from two tables.
1. Write an SQL query to find the second-highest salary.
Answer:
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
This query excludes the highest salary and finds the next highest.
2. Write a query to fetch the top 5 highest salaries from the employees table.
Answer:
SELECT salary FROM employees
ORDER BY salary DESC
LIMIT 5;
This sorts salaries in descending order and selects the top 5 values.
3. How to get the department-wise highest salary of employees?
Answer:
SELECT department_id, MAX(salary) AS highest_salary
FROM employees
GROUP BY department_id;
This groups employees by department_id and finds the highest salary in each department.
4. Write an SQL query to find duplicate records in a table.
Answer:
SELECT name, COUNT(*)
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;
This finds names that appear more than once, identifying duplicates.
5. Write a query to delete duplicate rows while keeping only one copy.
Answer:
DELETE FROM employees
WHERE id NOT IN (
SELECT MIN(id) FROM employees GROUP BY name
);
This keeps only the first occurrence and deletes duplicates.
6. Write a query to fetch employees who joined in the last 6 months.
Answer:
SELECT * FROM employees
WHERE join_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
This selects employees who joined in the last 6 months.
7. How do you fetch records where salary is between 50,000 and 1,00,000?
Answer:
SELECT * FROM employees
WHERE salary BETWEEN 50000 AND 100000;
This selects employees whose salary falls in the given range.
8. Write an SQL query to find employees who do not have a manager.
Answer:
SELECT * FROM employees
WHERE manager_id IS NULL;
This selects employees without a manager (NULL values).
9. Write a query to fetch employees with the same salary as another employee.
Answer:
SELECT e1.* FROM employees e1
JOIN employees e2 ON [Link] = [Link]
WHERE [Link] <> [Link];
This joins the table with itself to find employees with matching salaries.
10. How to update employee salaries by 10% if their salary is below 50,000?
Answer:
UPDATE employees
SET salary = salary * 1.10
WHERE salary < 50000;
This increases salary by 10% for employees earning below 50,000.
11. How to find employees whose name starts with ‘A’?
Answer:
SELECT * FROM employees
WHERE name LIKE 'A%';
This selects employees whose name starts with 'A'.
12. Write a query to find the 3rd highest salary using the LIMIT clause.
Answer:
SELECT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
This skips the top 2 salaries and selects the next highest.
13. How to find the count of employees in each department?
Answer:
SELECT department_id, COUNT(*) AS total_employees
FROM employees
GROUP BY department_id;
This groups employees by department and counts them.
14. Write an SQL query to fetch even-numbered employee IDs.
Answer:
SELECT * FROM employees
WHERE MOD(id, 2) = 0;
This selects employees with even IDs.
15. Write a query to find employees who joined on a Monday.
Answer:
SELECT * FROM employees
WHERE DAYOFWEEK(join_date) = 2;
This checks if the join date falls on a Monday (2 represents Monday in SQL).
16. Write an SQL query to get the last 3 records from a table.
Answer:
SELECT * FROM employees
ORDER BY id DESC
LIMIT 3;
This sorts the table in descending order and picks the last 3 records.
17. Write a query to find employees whose salaries are more than the department
average.
Answer:
SELECT * FROM employees e
WHERE salary > (
SELECT AVG(salary) FROM employees WHERE department_id = e.department_id
);
This selects employees whose salary is higher than the department’s average salary.
18. How to fetch the first character of an employee’s name?
Answer:
SELECT LEFT(name, 1) FROM employees;
This returns the first letter of each employee’s name.
19. How to calculate the total salary paid to all employees?
Answer:
SELECT SUM(salary) AS total_salary FROM employees;
This sums up all salaries to get the total payroll amount.
20. Write an SQL query to list employees and their manager’s name.
Answer:
SELECT [Link] AS employee_name, [Link] AS manager_name
FROM employees e
LEFT JOIN employees m ON e.manager_id = [Link];
This joins employees with their managers using LEFT JOIN.
21. Write a query to swap two employees' salaries.
Answer:
UPDATE employees
SET salary = CASE
WHEN id = 101 THEN (SELECT salary FROM employees WHERE id = 102)
WHEN id = 102 THEN (SELECT salary FROM employees WHERE id = 101)
END
WHERE id IN (101, 102);
This swaps salaries of employees with ID 101 and 102.
22. Write a query to display the current timestamp.
Answer:
SELECT NOW();
This returns the current date and time.
23. How to fetch employees who were hired in the last 30 days?
Answer:
SELECT * FROM employees
WHERE join_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);
This selects employees who joined in the last 30 days.
24. Write an SQL query to find employees who have the same joining date.
Answer:
SELECT join_date, COUNT(*)
FROM employees
GROUP BY join_date
HAVING COUNT(*) > 1;
This finds dates where more than one employee joined.
25. How to find employees who have not received a salary yet?
Answer:
SELECT * FROM employees
WHERE salary IS NULL;
This finds employees without a salary record.
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
Search...
Python Course Python Tutorial Interview Questions Python Quiz Python Glossary Python Proje
30 OOPs Interview Questions and Answers [2025
Updated]
Last Updated : 30 Apr, 2025
Object-oriented programming, or OOPs, is a programming paradigm
that implements the concept of objects in the program. It aims to
provide an easier solution to real-world problems by implementing real-
world entities such as inheritance, abstraction, polymorphism, etc. in
programming. OOPs concept is widely used in many popular languages
like Java, Python, C++, etc.
List of 30 Best OOPs Interview Questions with
Answers
In the upcoming section, you will get hands-on with the most asked
interview questions on Object-oriented programming with their perfect
answers. So, if you are a beginner and experienced in programming go
through the questions and ace your upcoming interviews.
1. What is Object Oriented Programming (OOPs)?
Object Oriented Programming is a programming paradigm where the
complete software operates as a bunch of objects talking to each other.
An object is a collection of data and the methods which operate on that
data.
2. Why OOPs?
The main advantage of OOP is better manageable code that covers the
following:
1. The overall understanding of the software is increased as the
distance between the language spoken by developers and that
[Link] 1/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
spoken by users.
2. Object orientation eases maintenance by the use of
encapsulation. One can easily change the underlying representation
by keeping the methods the same.
3. The OOPs paradigm is mainly useful for relatively big software.
3. What other paradigms of programming exist besides OOPs?
The programming paradigm is referred to the technique or approach of
writing a program. The programming paradigms can be classified into
the following types:
1. Imperative Programming Paradigm
It is a programming paradigm that works by changing the program state
through assignment statements. The main focus in this paradigm is on
how to achieve the goal. The following programming paradigms come
under this category:
1. Procedural Programming Paradigm: This programming paradigm is
based on the procedure call concept. Procedures, also known as
routines or functions are the basic building blocks of a program in
this paradigm.
2. Object-Oriented Programming or OOP: In this paradigm, we
visualize every entity as an object and try to structure the program
based on the state and behavior of that object.
3. Parallel Programming: The parallel programming paradigm is the
processing of instructions by dividing them into multiple smaller
[Link] 2/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
parts and executing them concurrently.
2. Declarative Programming Paradigm
Declarative programming focuses on what is to be executed rather than
how it should be executed. In this paradigm, we express the logic of a
computation without considering its control flow. The declarative
paradigm can be further classified into:
1. Logical Programming Paradigm: It is based on formal logic where
the program statements express the facts and rules about the
problem in the logical form.
2. Functional Programming Paradigm: Programs are created by
applying and composing functions in this paradigm.
3. Database Programming Paradigm: To manage data and information
organized as fields, records, and files, database programming models
are utilized.
4. What is the difference between Structured Programming and
Object-Oriented Programming?
Structured Programming is a technique that is considered a precursor to
OOP and usually consists of well-structured and separated modules. It
is a subset of procedural programming. The difference between OOPs
and Structured Programming is as follows:
Object-Oriented Structural Programming
Programming
A program's logical structure is
Programming that is object-
provided by structural programming,
oriented is built on objects
which divides programs into their
having a state and behavior.
corresponding functions.
It follows a bottom-to-top
It follows a Top-to-Down approach.
approach.
[Link] 3/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
Object-Oriented Structural Programming
Programming
Restricts the open flow of data
No restriction to the flow of data.
to authorized parts only
Anyone can access the data.
providing better data security.
Enhanced code reusability due
Code reusability is achieved by using
to the concepts of
functions and loops.
polymorphism and inheritance.
Methods work dynamically,
making calls based on object Functions are called sequentially, and
behavior and the need of the code lines are processed step by step.
code at runtime.
Modifying and updating the Modifying the code is difficult as
code is easier. compared to OOPs.
Data is given more importance
Code is given more importance.
in OOPs.
5. What are some commonly used Object-Oriented
Programming Languages?
OOPs paradigm is one of the most popular programming paradigms. It
is widely used in many popular programming languages such as:
C++
Java
Python
JavaScript
C#
Ruby
6. What are the advantages and disadvantages of OOPs?
[Link] 4/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
Advantages of OOPs Disadvantages of OOPs
The programmer should be well-skilled
OOPs provides enhanced and should have excellent thinking in
code reusability. terms of objects as everything is treated
as an object in OOPs.
The code is easier to maintain Proper planning is required because
and update. OOPs is a little bit tricky.
It provides better data
security by restricting data OOPs concept is not suitable for all kinds
access and avoiding of problems.
unnecessary exposure.
Fast to implement and easy
The length of the programs is much
to redesign resulting in
larger in comparison to the procedural
minimizing the complexity of
approach.
an overall program.
7. What is a Class?
A class is a building block of Object-Oriented Programs. It is a user-
defined data type that contains the data members and member
functions that operate on the data members. It is like a blueprint or
template of objects having common properties and methods.
8. What is an Object?
An object is an instance of a class. Data members and methods of a
class cannot be used directly. We need to create an object (or instance)
of the class to use them. In simple terms, they are the actual world
entities that have a state and behaviour.
C++ Java Python C#
1 # class definition
2 class Student:
[Link] 5/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
3 name = ""
4
5 # creating object
6 student1 = Student()
7 [Link] = "Rahul";
8
9 print("[Link]: " + [Link]);
Output
[Link]: Rahul
9. What are the main features of OOPs?
The main feature of the OOPs, also known as 4 pillars or basic
principles of OOPs are as follows:
1. Encapsulation
2. Data Abstraction
3. Polymorphism
4. Inheritance
OOPs Main Features
10. What is Encapsulation?
Encapsulation is the binding of data and methods that manipulate them
into a single unit such that the sensitive data is hidden from the users
[Link] 6/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
It is implemented as the processes mentioned below:
1. Data hiding: A language feature to restrict access to members of an
object. For example, private and protected members in C++.
2. Bundling of data and methods together: Data and methods that
operate on that data are bundled together. For example, the data
members and member methods that operate on them are wrapped
into a single unit known as a class.
11. What is Abstraction?
Abstraction is similar to data encapsulation and is very important in
OOP. It means showing only the necessary information and hiding the
other irrelevant information from the user. Abstraction is implemented
using classes and interfaces.
[Link] 7/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
12. What is Inheritance? What is its purpose?
The idea of inheritance is simple, a class is derived from another class
and uses data and implementation of that other class. The class which
is derived is called child or derived or subclass and the class from which
the child class is derived is called parent or base or superclass.
The main purpose of Inheritance is to increase code reusability. It is also
used to achieve Runtime Polymorphism.
13. What is Polymorphism? and types of Polymorphism?
The word "Polymorphism" means having many forms. It is the property
of some code to behave differently for different contexts. For example,
in C++ language, we can define multiple functions having the same
name but different working depending on the context.
Polymorphism can be classified into two types based on the time when
the call to the object or function is resolved. They are as follows:
Compile Time Polymorphism
Runtime Polymorphism
A) Compile-Time Polymorphism
Compile time polymorphism, also known as static polymorphism or
early binding is the type of polymorphism where the binding of the call
[Link] 8/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
to its code is done at the compile time. Method overloading or operator
overloading are examples of compile-time polymorphism.
B) Runtime Polymorphism
Also known as dynamic polymorphism or late binding, runtime
polymorphism is the type of polymorphism where the actual
implementation of the function is determined during the runtime or
execution. Function overriding is an example of this method.
14. What are access specifiers? What is their significance in
OOPs?
Access specifiers are special types of keywords that are used to specify
or control the accessibility of entities like classes, methods, and so on.
Private, Public, and Protected are examples of access specifiers or
access modifiers.
The key components of OOPs, encapsulation and data hiding, are
largely achieved because of these access specifiers.
15. What is the difference between overloading and overriding?
A compile-time polymorphism feature called overloading allows an
entity to have numerous implementations of the same name. Method
overloading and operator overloading are two examples.
Overriding is a form of runtime polymorphism where an entity with the
same name but a different implementation is executed. It is
implemented with the help of virtual functions.
16. Are there any limitations on Inheritance?
Yes, there are more challenges when you have more authority. Although
inheritance is a very strong OOPs feature, it also has significant
drawbacks.
As it must pass through several classes to be implemented,
inheritance takes longer to process.
[Link] 9/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
The base class and the child class, which are both engaged in
inheritance, are also closely related to one another (called tightly
coupled). Therefore, if changes need to be made, they may need to
be made in both classes at the same time.
Implementing inheritance might be difficult as well. Therefore, if not
implemented correctly, this could result in unforeseen mistakes or
inaccurate outputs.
17. What different types of Inheritance are there?
Inheritance can be classified into 5 types which are as follows:
1. Single Inheritance: Child class derived directly from the base class
2. Multiple Inheritance: Child class derived from multiple base classes.
3. Multilevel Inheritance: Child class derived from the class which is
also derived from another base class.
4. Hierarchical Inheritance: Multiple child classes derived from a single
base class.
5. Hybrid Inheritance: Inheritance consisting of multiple inheritance
types of the above specified.
Note: Type of inheritance supported is dependent on the
language. For example, Java does not support multiple
inheritance.
18. What is an interface?
[Link] 10/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
A unique class type known as an interface contains methods but not
their definitions. Inside an interface, only method declaration is
permitted. You cannot make objects using an interface. Instead, you
must put that interface into use and specify the procedures for doing so.
19. How is an abstract class different from an interface?
Both abstract classes and interfaces are special types of classes that
just include the declaration of the methods, not their implementation.
An abstract class is completely distinct from an interface, though.
Following are some major differences between an abstract class and an
interface.
Abstract Class Interface
A class that is abstract can have both An interface can only have
abstract and non-abstract methods. abstract methods.
An abstract class can have final, non- The interface has only static
final, static and non-static variables. and final variables.
Abstract class doesn't support multiple An interface supports
inheritance multiple inheritance.
20. How much memory does a class occupy?
Classes do not use memory. They merely serve as a template from
which items are made. Now, objects actually initialize the class
members and methods when they are created, using memory in the
process.
21. Is it always necessary to create objects from class?
No. If the base class includes non-static methods, an object must be
constructed. But no objects need to be generated if the class includes
[Link] 11/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
static methods. In this instance, you can use the class name to directly
call those static methods.
22. What is the difference between a structure and a class in
C++?
The structure is also a user-defined datatype in C++ similar to the class
with the following differences:
The major difference between a structure and a class is that in a
structure, the members are set to public by default while in a class,
members are private by default.
The other difference is that we use struct for declaring structure and
class for declaring a class in C++.
23. What is Constructor?
A constructor is a block of code that initializes the newly created object.
A constructor resembles an instance method but it’s not a method as it
doesn’t have a return type. It generally is the method having the same
name as the class but in some languages, it might differ. For example:
In python, a constructor is named __init__.
In C++ and Java, the constructor is named the same as the class name.
Example:
[Link] 12/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
C++ Java Python C#
1 class base:
2 def __init__(self):
3 print("This is a constructor")
24. What are the various types of constructors in C++?
The most common classification of constructors includes:
1. Default Constructor
2. Non-Parameterized Constructor
3. Parameterized Constructor
4. Copy Constructor
1. Default Constructor
The default constructor is a constructor that doesn't take any
arguments. It is a non-parameterized constructor that is automatically
defined by the compiler when no explicit constructor definition is
provided.
It initializes the data members to their default values.
2. Non-Parameterized Constructor
It is a user-defined constructor having no arguments or parameters.
Example:
C++ Java Python C#
1 class base:
2 def __init__(self):
3 print("This is a non-parameterized constructor")
3. Parameterized Constructor
The constructors that take some arguments are known as
parameterized constructors.
Example:
C++ Java Python C#
l b
[Link] 13/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
1 class base:
2 def __init__(self, a):
3 print("Constructor with argument: {}".format(a))
4. Copy Constructor
A copy constructor is a member function that initializes an object using
another object of the same class.
Example:
C++ Java Python C#
1 class Base:
2 def __init__(self, a=0, b=0):
3 self.a = a
4 self.b = b
5
6 # Copy constructor in Python
7 def __copy__(self):
8 return Base(self.a, self.b)
In Python, we do not have built-in copy constructors like Java and C++
but we can make a workaround using different methods.
25. What is a destructor?
A destructor is a method that is automatically called when the object
goes out of scope or destroyed.
In C++, the destructor name is also the same as the class name but with
the (~) tilde symbol as the prefix.
In Python, the destructor is named __del__.
Example:
C++ Java Python C#
1 class base:
2 def __del__(self):
3 print("This is destructor")
In Java, the garbage collector automatically deletes the useless objects
[Link] 14/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
so there is no concept of destructor in Java. We could have used
finalize() method as a workaround for the java destructor, but it is also
deprecated since Java 9.
26. Can we overload the constructor in a class?
Yes We can overload the constructor in a class in Java. Constructor
Overloading is done when we want constructor with different
constructor with different parameter (Number and Type).
27. Can we overload the destructor in a class?
No, a destructor cannot be overloaded in a class. There can only be one
destructor present in a class.
28. What are friend functions and friend classes?
Friend Functions: A friend function is a special function that is allowed
to access private and protected data of a class, even though it's not a
member of the class.
Friend Class: A friend class is a class that can access the private and
protected members of another class. It's like allowing a trusted friend or
a group of friends to see and change your personal information, which
others cannot.
29. What is the virtual function and pure virtual function?
A virtual function is a function that is used to override a method of the
parent class in the derived class. It is used to provide abstraction in a
class.
In C++ and C#, a virtual function is declared using the virtual
keyword,
In Java, every public, non-static, and non-final method is a virtual
function.
Python methods are always virtual.
[Link] 15/21
5/26/25, 9:24 AM 30 OOPs Interview Questions and Answers [2025 Updated] | GeeksforGeeks
Example:
C++ Java Python C#
1 class base:
2 def func(self):
3 print("This is a virtual function")
A pure virtual function, also known as an abstract function, is a member
function that doesn't contain any statements. This function is defined in
the derived class if needed.
Example:
C++ Java C#
1 class base {
2 virtual void pureVirFunc() = 0;
3 }
In Python, we achieve this using @abstractmethod from the ABC
(Abstract Base Class) module.
30. What is an abstract class?
In general terms, an abstract class is a class that is intended to be used
for inheritance. It cannot be instantiated. An abstract class can consist of
both abstract and non-abstract methods.
In C++, an abstract class is a class that contains at least one pure
virtual function.
In Java and C#, an abstract class is declared with an abstract
keyword.
Example:
C++ Java C#
1 class absClass {
2 public:
3 virtual void pvFunc() = 0;
4 }
[Link] 16/21
[Link] of a String:
# Original string
str = "Automation"
# Reversed string using slicing
reversed_str = str[::-1]
print(reversed_str)
# Original string
str = "Automation"
# Reversed string using reversed() and join()
reversed_str = ''.join(reversed(str))
print(reversed_str)
# Original string
str = "Automation"
# Initialize an empty string for the reversed string
reversed_str = ""
# Loop through the string in reverse order and build the reversed string
for char in str:
reversed_str = char + reversed_str # Prepend each character
print(reversed_str)
Palindrome:
For numbers
# Numeric value (you can change this to any number)
num = 121
# Convert the number to a string
num_str = str(num)
# Check if the string is the same as its reverse
if num_str == num_str[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
FOR STRING
test_str = "madam"
if test_str == test_str[::-1]:
print(f"'{test_str}' is a palindrome.")
else:
print(f"'{test_str}' is not a palindrome.")
FIBONACCI SERIES
n = 10
a, b = 0, 1
print("Fibonacci Series up to", n, "terms:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
FACTORIAL OF A NUMBER:
n = 5 # You can change this to any number
factorial = 1
for i in range(1, n + 1): # loop through 1 to n
factorial *= i
print(f"The factorial of {n} is {factorial}")
USING RECURSSION
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
# Test
n=5
result = factorial(n)
print(f"The factorial of {n} is {result}")
PRIME NUMBER CHECK
# Number to check
n = 29 # You can change this to any number
is_prime = True
if n <= 1:
is_prime = False
for i in range(2, n):
if n % i == 0:
is_prime = False
break
if is_prime:
print(f"{n} is a prime number.")
else:
print(f"{n} is not a prime number.")
VOWELS AND CONSONANTS IN A STRING
text = "Hello World"
vowels_count = 0
consonants_count = 0
for char in [Link]():
if char in 'aeiou':
vowels_count += 1
elif [Link]():
consonants_count += 1
print(f"Vowels: {vowels_count}")
print(f"Consonants: {consonants_count}")
SORT OF AN ARRAY:
arr = [64, 34, 25, 12, 22, 11, 90]
# Get the length of the array
n = len(arr)
# Bubble Sort Algorithm
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print("Sorted array:", arr)
MERGE OF TO ARRAYS:
# Two arrays to merge
arr1 = [1, 3, 5]
arr2 = [2, 4, 6]
merged_array = arr1 + arr2
print("Merged array:", merged_array)
# Two arrays to merge
arr1 = [1, 3, 5]
arr2 = [2, 4, 6]
for element in arr2:
[Link](element)
print("Merged array:", arr1)
# Two arrays to merge
arr1 = [1, 3, 5]
arr2 = [2, 4, 6]
[Link](arr2)
print("Merged array:", arr1)
LARGEST ELEMENT IN ARRAY:
arr = [64, 25, 75, 12, 22, 90]
largest = arr[0]
for num in arr:
if num > largest:
largest = num
print("The largest element is:", largest)
another is [Link]() lar=arr[-1] print(lar)
SECOND LARGEST ELEMENT IN ARRAY:
arr = [64, 25, 75, 12, 22, 90]
# Sort the array in descending order
[Link](reverse=True)
second_largest = arr[1]
print("The second largest element is:", second_largest)
REMOVE DUPLICATES FROM ARRAY
arr = [1, 2, 3, 4, 2, 3, 5, 6, 4]
unique_arr = []
for num in arr:
if num not in unique_arr:
unique_arr.append(num)
print("Array without duplicates:", unique_arr)
another
arr
unique=list(arr(set)
print(unique)
ARMSTRONG NUMBER
# Number to check if it's Armstrong
num = 153
num_str = str(num)
num_digits = len(num_str)
sum_of_powers = 0
# Loop through each digit, raise it to the power of num_digits, and add to the sum
for digit in num_str:
sum_of_powers += int(digit) ** num_digits
# Check if the sum of powers is equal to the original number
if sum_of_powers == num:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
REVERSE OF A NUMBER
num = 12345 # You can change this to any number
reversed_num = 0
while num > 0:
digit = num % 10 # Extract the last digit
reversed_num = reversed_num * 10 + digit # Append the digit to the reversed number
num = num // 10 # Remove the last digit from num
print("Reversed number is:", reversed_num)
PRIME NUMBERS IN A RANGE
# Range of numbers to check (start, end)
start = 10
end = 50
print(f"Prime numbers between {start} and {end} are:")
for num in range(start, end + 1):
if num > 1:
is_prime = True
for i in range(2, int(num ** 0.5) + 1): # Check divisibility from 2 to sqrt(num)
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=' ')
SWAPPING OF TWO NUMBERS:
a=10
b=5
a=a+b
b=a-b
a=a-b
print(a,b)
PERFECT NUMBER:
# Number to check
num = 28 # You can change this to any number
# Initialize sum of divisors
divisors_sum = 1 # 1 is a divisor of every number
# Check divisors from 2 to num//2
for i in range(2, num // 2 + 1):
if num % i == 0: # If i is a divisor of num
divisors_sum += i
# Check if the sum of divisors equals the number
if divisors_sum == num:
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")
SUM OF DIGITS IN A NUM:
n=234
s=0
while(n>0):
r=n%10
s=s+r
n=n//10
print(s)
LENGTH OF A STRING
str='hello'
r=len(str)
print(r)
CHECK IF STRING IS EMPTY:
s = ""
if s == "":
print("The string is empty")
else:
print("The string is not empty")
OCCURRENCE OF A CHARACTER IN STRING
s = "hello world"
char = 'o'
count = 0
for c in s:
if c == char:
count += 1
print(f"The character '{char}' appears {count} times.")
REMOVE ALL WHITE SPACES IN STRING:
s = "Hello world! This is a test."
s_no_spaces = [Link](" ", "")
print(s_no_spaces) # Output: "Helloworld!Thisisatest."
LEAP YEAR:
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
SUM OF N NATURAL NUMBERS:
n=5
s=0
for i in range(n+1):
s=s+i
print(s)
FREQUENCY OF CHARACTER IN A STRING:
string = "hello world"
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
print(frequency)
MOST OCCURRED CHARACTER IN STRING:
string = "hello world"
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
max_char = max(frequency, key=[Link])
print(f"The character with the maximum occurrence is '{max_char}' with {frequency[max_char]}
occurrences.")
oops concepts programs
exception handlings
oka name lo alternate names print cheyadam