0% found this document useful (0 votes)
2 views17 pages

Java Python AI ML Interview QA

The document is a Placement Interview Q&A Guide containing 120 frequently asked questions and answers across four topics: Java, Python, AI, and ML. It includes 30 questions for each topic, providing concise and interview-ready answers. The guide covers essential concepts, differences, and functionalities relevant to each programming language and technology.

Uploaded by

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

Java Python AI ML Interview QA

The document is a Placement Interview Q&A Guide containing 120 frequently asked questions and answers across four topics: Java, Python, AI, and ML. It includes 30 questions for each topic, providing concise and interview-ready answers. The guide covers essential concepts, differences, and functionalities relevant to each programming language and technology.

Uploaded by

twinkle.25mc020
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Placement Interview Q&A | Java • Python • AI • ML

PLACEMENT INTERVIEW Q&A GUIDE


30 Questions & Answers Each — Java, Python, AI, and ML
120 frequently asked placement interview questions with concise, interview-ready answers

Java • Python • AI • ML

Page 1
Placement Interview Q&A | Java • Python • AI • ML

Java — 30 Interview Questions & Answers


Q1. What is the difference between JVM, JRE, and JDK?
A: The JVM (Java Virtual Machine) executes Java bytecode and provides platform
independence. The JRE (Java Runtime Environment) includes the JVM plus core libraries
needed to run Java applications. The JDK (Java Development Kit) includes the JRE plus
development tools like the compiler (javac), needed to write and compile Java programs.
Q2. Why is Java called platform independent?
A: Java source code is compiled into an intermediate form called bytecode, which runs on
any device with a compatible JVM, regardless of the underlying operating system or
hardware — 'write once, run anywhere.'
Q3. What is JIT compilation?
A: The Just-In-Time (JIT) compiler is part of the JVM that compiles frequently executed
bytecode into native machine code at runtime, improving performance compared to pure
interpretation.
Q4. What are the main features of Java?
A: Java is object-oriented, platform-independent, robust (strong memory management and
exception handling), secure, multithreaded, and automatically manages memory via
garbage collection.
Q5. What is the difference between == and .equals() in Java?
A: == compares references (memory addresses) for objects, or actual values for primitives.
.equals() compares the logical/content equality of two objects, and can be overridden (as
String and most wrapper classes do) to compare actual values rather than references.
Q6. What is the difference between an abstract class and an interface?
A: An abstract class can have both abstract and concrete methods, constructors, and
instance variables, and supports only single inheritance. An interface traditionally declares
only method signatures (modern Java allows default/static methods too), supports multiple
inheritance, and represents a pure contract of behavior.
Q7. What is the difference between method overloading and overriding?
A: Overloading is defining multiple methods with the same name but different parameter
lists within the same class, resolved at compile time. Overriding is a subclass providing its
own implementation of a method already defined in its superclass, resolved at run time via
dynamic dispatch.
Q8. What is the use of the 'final' keyword?
A: A final variable cannot be reassigned once initialized, a final method cannot be
overridden by a subclass, and a final class cannot be extended/subclassed — used to
enforce immutability or prevent unwanted inheritance.

Page 2
Placement Interview Q&A | Java • Python • AI • ML

Q9. What is the difference between final, finally, and finalize?


A: final is a keyword used to restrict reassignment, overriding, or inheritance. finally is a
block that always executes after a try-catch, used for cleanup code. finalize() is a method
called by the garbage collector before an object is destroyed (though its use is discouraged
in modern Java in favor of try-with-resources).
Q10. What is a constructor, and how is it different from a method?
A: A constructor initializes a new object and shares the class's name with no return type,
invoked automatically when an object is created via 'new'. A method is a named block of
reusable logic that must be called explicitly and always has a return type (or void).
Q11. What is the difference between static and instance members?
A: Static members belong to the class itself and are shared across all instances (accessed
via [Link]). Instance members belong to individual objects, with each object
having its own copy, accessed via an object reference.
Q12. What is the 'this' keyword used for?
A: 'this' refers to the current object instance, commonly used to distinguish instance
variables from parameters with the same name, to call another constructor in the same class
(this(...)), or to pass the current object as an argument.
Q13. What is the 'super' keyword used for?
A: 'super' refers to the immediate parent class, used to call the parent's constructor
(super(...)), access a parent's overridden method ([Link]()), or access a parent's field
hidden by the subclass.
Q14. How does exception handling work in Java?
A: Code that might throw an exception is placed in a try block; catch blocks handle specific
exception types that occur; a finally block (optional) always executes regardless of whether
an exception occurred, typically used for cleanup; 'throw' raises an exception explicitly,
and 'throws' declares that a method might propagate an exception.
Q15. What is the difference between checked and unchecked exceptions?
A: Checked exceptions (e.g., IOException) are checked at compile time and must be either
caught or declared with 'throws'. Unchecked exceptions (e.g., NullPointerException,
ArithmeticException) are subclasses of RuntimeException and are not required to be
declared or caught, typically representing programming errors.
Q16. What is the difference between ArrayList and LinkedList?
A: ArrayList is backed by a dynamic array, offering fast O(1) random access but slower
O(n) insertions/deletions in the middle. LinkedList is a doubly linked list, offering fast O(1)
insertions/deletions at known positions but slower O(n) random access.
Q17. What is the difference between HashMap and Hashtable?

Page 3
Placement Interview Q&A | Java • Python • AI • ML

A: HashMap is not synchronized (not thread-safe by default) and allows one null key and
multiple null values, generally offering better performance. Hashtable is synchronized
(thread-safe) and does not allow null keys or values — in modern code,
ConcurrentHashMap is usually preferred over Hashtable for thread safety.
Q18. What is the difference between HashSet and TreeSet?
A: HashSet stores unique elements with no guaranteed order, offering O(1) average
add/lookup via hashing. TreeSet stores unique elements in sorted order (via a red-black
tree), offering O(log n) operations but maintaining a sorted iteration order.
Q19. How do you create a thread in Java?
A: Either extend the Thread class and override run(), or implement the Runnable interface
and pass it to a Thread object — implementing Runnable is generally preferred since Java
doesn't support multiple inheritance of classes, and it decouples the task from the threading
mechanism.
Q20. What is synchronization in Java?
A: Synchronization controls access to a shared resource by multiple threads, using the
'synchronized' keyword on a method or block, ensuring only one thread can execute that
critical section at a time to prevent race conditions.
Q21. What is the difference between wait() and sleep()?
A: wait() (called on an object) releases the lock it holds and pauses the thread until notified,
used for inter-thread communication within synchronized blocks. sleep() (a static Thread
method) pauses the current thread for a fixed time without releasing any lock it holds.
Q22. What is garbage collection in Java?
A: Garbage collection is the JVM's automatic process of reclaiming memory occupied by
objects that are no longer reachable/referenced by the program, freeing developers from
manual memory management (unlike languages such as C/C++).
Q23. What is the difference between String, StringBuilder, and StringBuffer?
A: String is immutable — every modification creates a new object. StringBuilder is
mutable and not thread-safe, offering better performance for single-threaded string
manipulation. StringBuffer is mutable and thread-safe (synchronized methods), useful
when strings are modified across multiple threads.
Q24. Why is String immutable in Java?
A: Immutability makes String instances safe to share and cache (via the string pool),
thread-safe by default, and secure for use as keys in hash-based collections or in security-
sensitive contexts like class loading and network connections, since their value can never
unexpectedly change.
Q25. What is the Java String pool?

Page 4
Placement Interview Q&A | Java • Python • AI • ML

A: The String pool is a special memory region in the heap where the JVM stores unique
String literals; when a new String literal is created, Java checks the pool first and reuses an
existing object if the value already exists, saving memory.
Q26. What is autoboxing and unboxing?
A: Autoboxing is the automatic conversion of a primitive type into its corresponding
wrapper object (e.g., int to Integer). Unboxing is the reverse — converting a wrapper object
back into its primitive type — both handled automatically by the compiler since Java 5.
Q27. What are varargs in Java?
A: Varargs (variable-length arguments), written as Type... paramName, let a method
accept zero or more arguments of a given type as if they were an array, providing flexibility
without requiring method overloading for different argument counts.
Q28. What is an enum in Java?
A: An enum is a special data type that represents a fixed set of named constants (e.g.,
DAYS { MONDAY, TUESDAY, ... }), providing type safety compared to using plain
integers or strings for such fixed sets of values.
Q29. What is a functional interface, and what is a lambda expression?
A: A functional interface is an interface with exactly one abstract method (e.g., Runnable,
Comparator), which can be implemented concisely using a lambda expression — a
compact anonymous function syntax like (a, b) -> a + b — introduced in Java 8 to support
functional-style programming.
Q30. What is the Java Streams API?
A: Introduced in Java 8, the Streams API provides a functional-style way to process
sequences of elements (e.g., from a collection) using operations like filter, map, and reduce,
chained in a pipeline, often improving readability and enabling easier parallel processing
compared to explicit loops.

Page 5
Placement Interview Q&A | Java • Python • AI • ML

Python — 30 Interview Questions & Answers


Q1. What is the difference between a list and a tuple?
A: A list is mutable (can be modified after creation) and defined with square brackets [].
A tuple is immutable (cannot be changed after creation) and defined with parentheses ();
tuples are generally faster and can be used as dictionary keys, unlike lists.
Q2. What are mutable and immutable data types in Python?
A: Mutable types can be changed in place after creation (list, dict, set). Immutable types
cannot be changed once created — any 'modification' creates a new object (int, float, str,
tuple, frozenset).
Q3. What is the difference between a shallow copy and a deep copy?
A: A shallow copy ([Link]()) creates a new object but inserts references to the same
nested objects as the original, so changes to nested objects affect both. A deep copy
([Link]()) recursively copies all nested objects, making the copy fully
independent.
Q4. What are *args and **kwargs?
A: *args allows a function to accept any number of positional arguments, collected into a
tuple. **kwargs allows a function to accept any number of keyword arguments, collected
into a dictionary — both provide flexible function signatures.
Q5. What is a lambda function?
A: A lambda is a small, anonymous, single-expression function defined with the lambda
keyword (e.g., lambda x: x * 2), commonly used for short operations passed to functions
like map(), filter(), or sorted()'s key argument.
Q6. What are Python decorators?
A: A decorator is a function that wraps another function to extend or modify its behavior
without changing its source code, applied using the @decorator_name syntax above a
function definition — commonly used for logging, timing, or access control.
Q7. What is the difference between a generator and a normal function?
A: A normal function computes and returns all its results at once. A generator uses the
'yield' keyword to produce values one at a time, lazily, pausing its state between calls —
this is more memory-efficient for large or infinite sequences.
Q8. What is list comprehension?
A: List comprehension is a concise syntax for creating a new list by applying an expression
to each item in an iterable, optionally with a filter condition — e.g., [x*x for x in range(10)
if x % 2 == 0] — typically more readable and faster than an equivalent for-loop.
Q9. What is the difference between == and is in Python?

Page 6
Placement Interview Q&A | Java • Python • AI • ML

A: == compares whether two objects have equal values. 'is' compares whether two
references point to the exact same object in memory (identity comparison) — two equal-
valued objects can still be different objects in memory.
Q10. What is the Global Interpreter Lock (GIL)?
A: The GIL is a mutex in CPython that allows only one thread to execute Python bytecode
at a time within a single process, which limits true parallelism for CPU-bound
multithreaded programs — CPU-bound work typically uses multiprocessing instead to
bypass this limitation.
Q11. What is the difference between a module and a package?
A: A module is a single Python file (.py) containing definitions and code that can be
imported. A package is a directory containing multiple related modules along with an
__init__.py file, organizing code into a hierarchical namespace.
Q12. What is 'self' in Python classes?
A: 'self' is the conventional name for the first parameter of an instance method, referring
to the specific instance the method is being called on — it lets methods access and modify
that instance's attributes.
Q13. What is the __init__ method?
A: __init__ is Python's constructor method, automatically called when a new object is
instantiated, typically used to initialize the object's instance attributes with values passed
in as arguments.
Q14. What is the difference between class variables and instance variables?
A: Class variables are shared across all instances of a class (defined directly in the class
body). Instance variables are unique to each object (typically defined inside __init__ using
[Link]), with each instance holding its own copy.
Q15. What is multiple inheritance, and what is MRO?
A: Multiple inheritance lets a class inherit from more than one parent class. The Method
Resolution Order (MRO) is the specific order Python follows (via the C3 linearization
algorithm) to search parent classes for a method or attribute, resolvable via
ClassName.__mro__ or the mro() method.
Q16. What is the difference between @staticmethod and @classmethod?
A: A @staticmethod doesn't receive an implicit first argument (no access to the instance
or class) and behaves like a plain function namespaced inside the class. A @classmethod
receives the class itself as its first argument (conventionally 'cls'), allowing it to access or
modify class-level state.
Q17. What do map(), filter(), and reduce() do?
A: map(func, iterable) applies a function to every item in an iterable, returning transformed
results. filter(func, iterable) keeps only items for which the function returns True.
Page 7
Placement Interview Q&A | Java • Python • AI • ML

reduce(func, iterable) (from functools) cumulatively applies a function to reduce an iterable


to a single value.
Q18. How does exception handling work in Python?
A: Code that might raise an exception is placed in a try block; except blocks catch and
handle specific exception types; an optional else block runs if no exception occurred; a
finally block always runs regardless, typically for cleanup — custom exceptions can be
created by subclassing Exception.
Q19. How do you handle files in Python?
A: Use the built-in open(filename, mode) function to get a file object, then
read()/readline()/readlines() or write()/writelines() as needed; using the 'with open(...) as f:'
context manager is preferred since it automatically closes the file even if an error occurs.
Q20. What is a context manager (the 'with' statement)?
A: A context manager handles setup and teardown logic automatically around a block of
code (e.g., opening and closing a file, or acquiring and releasing a lock), implemented via
__enter__ and __exit__ methods, and invoked using the 'with' statement for cleaner, safer
resource management.
Q21. What is slicing in Python?
A: Slicing extracts a portion of a sequence (list, string, tuple) using the syntax
sequence[start:stop:step], where start is inclusive, stop is exclusive, and step defines the
interval between elements — e.g., my_list[1:5:2].
Q22. What is the difference between a set and a list?
A: A list is ordered, allows duplicate elements, and is indexed. A set is unordered, stores
only unique elements, and offers faster O(1) average membership testing due to its hash-
based implementation, but doesn't support indexing.
Q23. What is the difference between an iterator and an iterable?
A: An iterable is any object capable of returning its members one at a time (implements
__iter__), such as a list or string. An iterator is the object produced by calling iter() on an
iterable, which implements __next__() to produce successive values and raises
StopIteration when exhausted.
Q24. What is the difference between append() and extend() for lists?
A: append() adds its entire argument as a single new element at the end of the list (even if
that argument is itself a list). extend() iterates over its argument and adds each of its
elements individually to the end of the list.
Q25. What is the purpose of if __name__ == '__main__': in a Python script?
A: It checks whether the script is being run directly (in which case __name__ equals
'__main__') versus being imported as a module into another script (in which case

Page 8
Placement Interview Q&A | Java • Python • AI • ML

__name__ equals the module's name) — code inside this block only runs when the file is
executed directly.
Q26. How does a Python dictionary work internally?
A: A dictionary is implemented as a hash table: each key is passed through a hash function
to compute an index where its value is stored, giving average O(1) time complexity for
lookups, insertions, and deletions, with collision handling for keys that hash to the same
index.
Q27. How do you create and use a custom exception in Python?
A: Define a new class that inherits from Exception (or a more specific built-in exception),
optionally overriding __init__ to add custom attributes/messages, then raise it using 'raise
CustomException("message")' and catch it with a specific except clause.
Q28. What is the difference between pass, continue, and break?
A: pass is a null operation used as a placeholder where syntax requires a statement but no
action is needed. continue skips the rest of the current loop iteration and moves to the next
one. break exits the loop entirely, regardless of the loop's condition.
Q29. What is a virtual environment, and why is it used?
A: A virtual environment (created via venv or virtualenv) is an isolated Python
environment with its own installed packages, separate from the system-wide Python
installation — used to avoid dependency conflicts between different projects requiring
different package versions.
Q30. What is duck typing in Python?
A: Duck typing means an object's suitability for use is determined by the presence of
certain methods/behavior rather than its explicit type — 'if it walks like a duck and quacks
like a duck, it's a duck' — allowing flexible, type-agnostic code as long as an object
supports the required operations.

Page 9
Placement Interview Q&A | Java • Python • AI • ML

Artificial Intelligence (AI) — 30 Interview Questions & Answers


Q1. What is Artificial Intelligence?
A: AI is the field of computer science focused on building systems that can perform tasks
that typically require human intelligence — such as reasoning, learning, perception, and
decision-making — by simulating or replicating aspects of human cognitive abilities.
Q2. What are the different types of AI?
A: Narrow AI (or Weak AI) performs a specific task well (e.g., voice assistants,
recommendation systems) and is what exists today. General AI (Strong AI) would match
human-level intelligence across any task, a theoretical goal not yet achieved. Super AI
would exceed human intelligence across all domains, a purely hypothetical future concept.
Q3. What is the Turing Test?
A: Proposed by Alan Turing, it's a test of a machine's ability to exhibit intelligent behavior
indistinguishable from a human — a human evaluator has text-based conversations with
both a human and a machine, and if they cannot reliably tell which is which, the machine
is said to have passed.
Q4. What is the difference between AI, Machine Learning, and Deep Learning?
A: AI is the broad goal of building intelligent systems. Machine Learning is a subset of AI
where systems learn patterns from data rather than being explicitly programmed with rules.
Deep Learning is a subset of ML using multi-layered neural networks, particularly effective
on unstructured data like images, audio, and text.
Q5. What is an intelligent agent?
A: An intelligent agent is anything that perceives its environment through sensors and acts
upon it through actuators to achieve specific goals — ranging from a simple thermostat to
a complex autonomous vehicle.
Q6. What are the main types of agents in AI?
A: Simple reflex agents act only on the current perception using condition-action rules.
Model-based agents maintain an internal state to handle partial observability. Goal-based
agents act to achieve defined goals. Utility-based agents choose actions that maximize a
measure of desirability. Learning agents improve their performance over time based on
experience.
Q7. Why is search important in AI, and what are common search algorithms?
A: Many AI problems (pathfinding, puzzle-solving, planning) can be framed as searching
through a space of possible states for a solution. Common algorithms include uninformed
searches like Breadth-First Search (BFS) and Depth-First Search (DFS), and informed
searches like A* that use heuristics to search more efficiently.
Q8. What is the difference between BFS and DFS?

Page 10
Placement Interview Q&A | Java • Python • AI • ML

A: Breadth-First Search (BFS) explores all nodes at the current depth before moving
deeper, guaranteeing the shortest path in unweighted graphs but using more memory.
Depth-First Search (DFS) explores as far as possible along a branch before backtracking,
using less memory but not guaranteeing the shortest path.
Q9. What is the A* search algorithm?
A: A* is an informed search algorithm that finds the shortest path by combining the actual
cost from the start node (g(n)) with a heuristic estimate of the cost to the goal (h(n)),
expanding nodes with the lowest f(n) = g(n) + h(n) first — efficient and optimal if the
heuristic is admissible (never overestimates).
Q10. What is a heuristic function?
A: A heuristic function estimates the cost or distance from a given state to the goal state,
guiding search algorithms to explore more promising paths first, trading some guarantee
of optimality for significant gains in search efficiency.
Q11. What is the minimax algorithm?
A: Minimax is a decision-making algorithm used in two-player, zero-sum games (like
chess or tic-tac-toe), where one player tries to maximize their score and the other tries to
minimize it, recursively exploring the game tree to choose the optimal move assuming the
opponent also plays optimally.
Q12. What is alpha-beta pruning?
A: Alpha-beta pruning is an optimization technique for the minimax algorithm that
eliminates branches of the game tree that cannot possibly influence the final decision,
significantly reducing the number of nodes evaluated without affecting the final result.
Q13. What is a Constraint Satisfaction Problem (CSP)?
A: A CSP is a problem defined by a set of variables, each with a domain of possible values,
and a set of constraints restricting which value combinations are allowed — the goal is to
find an assignment of values to variables that satisfies all constraints (e.g., Sudoku, map
coloring).
Q14. What is knowledge representation in AI?
A: Knowledge representation is how an AI system encodes information about the world
(facts, rules, relationships) in a form that can be used for reasoning — common approaches
include semantic networks, frames, logic-based representations, and ontologies/knowledge
graphs.
Q15. What is an expert system?
A: An expert system is an AI program that emulates the decision-making ability of a human
expert in a specific domain, typically consisting of a knowledge base (facts and rules) and
an inference engine that applies logical rules to the knowledge base to answer questions or
solve problems.

Page 11
Placement Interview Q&A | Java • Python • AI • ML

Q16. What is fuzzy logic?


A: Fuzzy logic is a form of reasoning that handles degrees of truth (partial membership
between 0 and 1) rather than strict binary true/false values, useful for modeling imprecise
or vague concepts like 'warm' or 'fast', commonly used in control systems.
Q17. What are genetic algorithms?
A: Genetic algorithms are optimization techniques inspired by natural selection — a
population of candidate solutions evolves over generations through selection, crossover
(combining solutions), and mutation, gradually improving toward better solutions for a
given problem.
Q18. What is Natural Language Processing (NLP)?
A: NLP is the field of AI focused on enabling computers to understand, interpret, and
generate human language, covering tasks like sentiment analysis, machine translation, text
summarization, and chatbots.
Q19. What is the difference between Natural Language Understanding (NLU) and
Natural Language Generation (NLG)?
A: NLU focuses on interpreting and extracting meaning from human language input (e.g.,
intent recognition in a chatbot). NLG focuses on producing coherent, human-like language
as output from structured data or internal representations (e.g., generating a text summary
or response).
Q20. What is computer vision?
A: Computer vision is the field of AI that enables computers to interpret and understand
visual information from images or video, covering tasks like object detection, image
classification, facial recognition, and image segmentation.
Q21. How does a typical chatbot work?
A: A chatbot typically processes user input through NLU to identify intent and extract
entities, uses a dialogue manager to determine the appropriate response or action based on
context, and then generates a reply via NLG or predefined templates — modern chatbots
increasingly use large language models for more flexible, open-ended conversation.
Q22. What is planning in AI?
A: Planning is the AI task of determining a sequence of actions that will move an agent
from an initial state to a desired goal state, given a set of possible actions and their effects
— used in robotics, logistics, and game AI.
Q23. What is a knowledge graph?
A: A knowledge graph represents information as a network of entities (nodes) and their
relationships (edges), enabling structured storage and reasoning over connected facts —
used by search engines and recommendation systems to understand relationships between
concepts.

Page 12
Placement Interview Q&A | Java • Python • AI • ML

Q24. What is the difference between rule-based systems and learning-based systems?
A: Rule-based systems rely on explicitly programmed if-then rules crafted by human
experts, making them predictable but inflexible to unforeseen scenarios. Learning-based
systems (machine learning) infer patterns directly from data, adapting to new scenarios but
requiring substantial training data and often being less interpretable.
Q25. What is reinforcement learning, conceptually?
A: Reinforcement learning is a type of learning where an agent learns to make decisions
by taking actions in an environment and receiving rewards or penalties as feedback,
gradually learning a policy that maximizes cumulative reward over time — used in
robotics, game-playing AI, and recommendation systems.
Q26. What are some key ethical concerns in AI?
A: Key concerns include algorithmic bias (models reflecting or amplifying biases present
in training data), lack of transparency/explainability in complex models, privacy
implications of large-scale data collection, potential job displacement, and questions of
accountability when AI systems make consequential decisions.
Q27. What is a semantic network?
A: A semantic network is a graph-based knowledge representation where nodes represent
concepts/objects and labeled edges represent relationships between them (e.g., 'Dog' --is_a-
-> 'Animal'), allowing an AI system to reason about relationships between concepts.
Q28. What is machine translation?
A: Machine translation is the AI task of automatically translating text or speech from one
language to another, historically done via rule-based or statistical methods, and now
dominated by neural machine translation models based on the Transformer architecture.
Q29. What is speech recognition, and what makes it challenging?
A: Speech recognition converts spoken language into text, and is challenging due to
variability in accents, background noise, overlapping speech, homophones, and the need to
model both acoustic signals and language structure simultaneously.
Q30. What is a multi-agent system?
A: A multi-agent system consists of multiple autonomous agents interacting within a
shared environment, which may cooperate or compete to achieve individual or collective
goals — used in domains like traffic simulation, distributed robotics, and multiplayer game
AI.

Page 13
Placement Interview Q&A | Java • Python • AI • ML

Machine Learning (ML) — 30 Interview Questions & Answers


Q1. What is Machine Learning?
A: Machine Learning is a subset of AI where systems learn patterns and relationships
directly from data, improving their performance on a task through experience, rather than
following explicitly programmed rules for every scenario.
Q2. What is supervised learning?
A: Supervised learning trains a model on labeled data — inputs paired with known correct
outputs — so the model learns to predict outputs for new, unseen inputs; common tasks
include classification and regression.
Q3. What is unsupervised learning?
A: Unsupervised learning trains a model on unlabeled data, finding hidden patterns,
groupings, or structure without predefined correct outputs; common tasks include
clustering and dimensionality reduction.
Q4. What is reinforcement learning?
A: Reinforcement learning trains an agent to make sequential decisions by interacting with
an environment, receiving rewards or penalties as feedback, and learning a policy that
maximizes cumulative long-term reward.
Q5. What is the difference between classification and regression?
A: Classification predicts a discrete category or class label (e.g., spam vs not spam).
Regression predicts a continuous numerical value (e.g., predicting house prices) — the
choice of algorithm and evaluation metrics differs based on which type of output is needed.
Q6. What is overfitting, and how do you prevent it?
A: Overfitting occurs when a model learns the training data too specifically, including its
noise, and performs poorly on new, unseen data. It can be reduced with more training data,
simpler models, regularization, dropout (in neural networks), early stopping, or cross-
validation.
Q7. What is underfitting?
A: Underfitting occurs when a model is too simple to capture the underlying patterns in
the data, resulting in poor performance on both training and test data — addressed by using
a more complex model, adding relevant features, or training longer.
Q8. What is the bias-variance tradeoff?
A: Bias is error from overly simplistic assumptions (leading to underfitting); variance is
error from excessive sensitivity to small fluctuations in training data (leading to
overfitting). The tradeoff is that reducing one often increases the other, so the goal is to
find a model complexity that balances both for the best generalization.
Q9. What is cross-validation?
Page 14
Placement Interview Q&A | Java • Python • AI • ML

A: Cross-validation (e.g., k-fold) evaluates a model's performance by splitting the data into
multiple subsets, training on some folds and validating on the remaining fold, repeating
this across all folds — giving a more reliable estimate of how the model generalizes than
a single train-test split.
Q10. Why do we need separate train, validation, and test sets?
A: The training set is used to fit the model's parameters. The validation set is used to tune
hyperparameters and make model-selection decisions without touching the test set. The
test set is held out entirely until the end to give an unbiased estimate of the final model's
performance on unseen data.
Q11. What is linear regression?
A: Linear regression models the relationship between a dependent variable and one or more
independent variables by fitting a straight line (or hyperplane) that minimizes the sum of
squared differences between predicted and actual values.
Q12. What is logistic regression, and why is it used for classification?
A: Despite its name, logistic regression is used for classification: it applies the sigmoid
function to a linear combination of inputs to output a probability between 0 and 1, which
is then thresholded to assign a class label — well suited for binary classification problems.
Q13. What is a decision tree?
A: A decision tree splits data recursively based on feature values, forming a tree of if-else
decisions, ending in leaf nodes that represent a predicted class or value — easy to interpret
but prone to overfitting if grown too deep.
Q14. What is a random forest, and how does it improve on a single decision tree?
A: A random forest is an ensemble of many decision trees, each trained on a random subset
of data and features (bagging), with the final prediction being a majority vote
(classification) or average (regression) across all trees — this reduces overfitting and
variance compared to a single deep tree.
Q15. What is a Support Vector Machine (SVM)?
A: An SVM finds the optimal hyperplane that best separates classes in the feature space,
maximizing the margin (distance) between the hyperplane and the nearest data points from
each class (support vectors); kernel functions allow SVMs to handle non-linearly separable
data.
Q16. What is K-Nearest Neighbors (KNN)?
A: KNN is a simple, instance-based algorithm that classifies (or predicts a value for) a new
data point based on the majority class (or average value) among its 'k' closest neighbors in
the training data, based on a distance metric like Euclidean distance.

Page 15
Placement Interview Q&A | Java • Python • AI • ML

Q17. What is K-Means clustering?


A: K-Means is an unsupervised algorithm that partitions data into k clusters by iteratively
assigning points to the nearest cluster centroid and then recalculating centroids as the mean
of assigned points, repeating until the assignments stabilize.
Q18. What is Principal Component Analysis (PCA)?
A: PCA is a dimensionality reduction technique that transforms correlated features into a
smaller set of uncorrelated variables (principal components), ordered by how much
variance in the data they explain — used to reduce dimensionality while preserving as
much information as possible.
Q19. What is gradient descent?
A: Gradient descent is an optimization algorithm that iteratively adjusts a model's
parameters in the direction that most reduces the loss function, using the gradient (slope)
of the loss with respect to each parameter; the learning rate controls the step size at each
iteration.
Q20. What is a confusion matrix?
A: A confusion matrix is a table summarizing a classification model's performance,
showing counts of true positives, true negatives, false positives, and false negatives — the
basis for computing metrics like accuracy, precision, recall, and F1-score.
Q21. What are precision, recall, and F1-score?
A: Precision is the fraction of predicted positives that are actually correct (TP / (TP + FP)).
Recall is the fraction of actual positives correctly identified (TP / (TP + FN)). F1-score is
the harmonic mean of precision and recall, useful when you need a single balanced metric,
especially with imbalanced classes.
Q22. What is ROC-AUC?
A: The ROC curve plots the true positive rate against the false positive rate at various
classification thresholds; AUC (Area Under the Curve) summarizes this into a single
number between 0 and 1, indicating how well the model distinguishes between classes —
1.0 is perfect, 0.5 is no better than random guessing.
Q23. What is regularization, and what is the difference between L1 and L2?
A: Regularization adds a penalty term to a model's loss function to discourage overly large
parameter weights and reduce overfitting. L1 (Lasso) adds the sum of absolute weight
values, which can shrink some weights to exactly zero (useful for feature selection). L2
(Ridge) adds the sum of squared weight values, shrinking weights smoothly toward zero
without eliminating them entirely.
Q24. What is feature scaling, and why is it needed?
A: Feature scaling (e.g., normalization or standardization) transforms features to a similar
scale/range, which is important for distance-based algorithms (KNN, SVM, K-Means) and

Page 16
Placement Interview Q&A | Java • Python • AI • ML

gradient-based optimization (neural networks), since features with larger raw ranges could
otherwise dominate the model unfairly.
Q25. What is one-hot encoding?
A: One-hot encoding converts a categorical variable into multiple binary columns, one per
category, with a 1 marking the present category and 0s elsewhere — allowing categorical
data to be used in algorithms that require numerical input without implying a false ordinal
relationship between categories.
Q26. What is the difference between bagging and boosting?
A: Bagging (e.g., Random Forest) trains multiple models independently and in parallel on
random subsets of data, then averages/votes their predictions to reduce variance. Boosting
(e.g., AdaBoost, Gradient Boosting, XGBoost) trains models sequentially, with each new
model focusing on correcting the errors of the previous ones, reducing bias.
Q27. What is Naive Bayes, and why is it called 'naive'?
A: Naive Bayes is a probabilistic classifier based on Bayes' Theorem. It's called 'naive'
because it assumes all features are conditionally independent of each other given the class
label — an assumption that's rarely fully true in practice, but the algorithm still performs
surprisingly well on many real-world problems, especially text classification.
Q28. What is hyperparameter tuning?
A: Hyperparameters are configuration settings not learned from data (e.g., learning rate,
number of trees, k in KNN). Hyperparameter tuning is the process of searching for the
combination of these settings that yields the best model performance, commonly done via
grid search, random search, or Bayesian optimization, evaluated using cross-validation.
Q29. What are activation functions in neural networks, and why are they needed?
A: Activation functions (e.g., ReLU, sigmoid, tanh, softmax) introduce non-linearity into
a neural network after each layer's linear transformation; without them, stacking multiple
layers would mathematically collapse into a single linear transformation, severely limiting
what the network could learn.
Q30. What is dropout, and why is it used in neural networks?
A: Dropout is a regularization technique that randomly 'drops' (deactivates) a fraction of
neurons during each training iteration, preventing the network from becoming overly
reliant on specific neurons and reducing overfitting by encouraging more robust,
distributed feature representations.
End of guide — 120 questions total (30 each: Java, Python, AI, ML).

Page 17

You might also like