Java_and_Python_Revision_Notes
Java_and_Python_Revision_Notes
Core Language Concepts + 90 Interview Questions (45 Java, 45 Python), Dense Print-Friendly Format
Part A covers Java, Part B covers Python, Part C is a quick head-to-head comparison. Rapid-Fire FAQ section at the very end has 45 questions
per language. Note: OOP fundamentals (encapsulation, inheritance, etc.) that apply to BOTH languages are assumed from the separate OOP
notes doc — this one focuses on what's specific to Java and Python.
• Unchecked exceptions (RuntimeException): not enforced by the
PART A — JAVA compiler (e.g., NullPointerException, ArrayIndexOutOfBoundsException)
— typically represent programming bugs rather than recoverable
A1. JVM, JDK & JRE
conditions.
• JVM (Java Virtual Machine): the runtime engine that executes compiled
• try-catch-finally: 'finally' block always runs, whether or not an exception
Java bytecode — this is what makes Java 'write once, run anywhere'
occurred (except in extreme cases like [Link]()) — used for cleanup
(bytecode runs on any platform with a JVM).
(closing files/connections).
• JDK (Java Development Kit): everything needed to DEVELOP Java
• try-with-resources: automatically closes resources (like file streams)
programs — includes the compiler (javac), JRE, and other dev tools.
that implement AutoCloseable, without needing an explicit finally block.
• JRE (Java Runtime Environment): everything needed to RUN a Java
• Custom exceptions: created by extending Exception (checked) or
program — includes the JVM and core libraries, but no compiler.
RuntimeException (unchecked) to represent application-specific error
• Compilation flow: .java source → javac compiles to .class bytecode → conditions.
JVM interprets/JIT-compiles bytecode to native machine code at runtime.
• JIT (Just-In-Time) compiler: part of the JVM that compiles A6. Collections Framework
frequently-run bytecode into native machine code at runtime for speed,
Interface Common Implementations Key Trait
rather than purely interpreting every time.
List ArrayList, LinkedList Ordered, allows duplicates
A2. Memory Model
Set HashSet, TreeSet, LinkedHashSet No duplicates
• Stack: stores method call frames, local variables, and primitive values —
memory is automatically reclaimed when a method returns. Map HashMap, TreeMap, LinkedHashMapKey-value pairs
• Heap: stores all objects (created via 'new') — managed by the Garbage
Queue LinkedList, PriorityQueue FIFO (or priority order)
Collector, not automatically freed on method return.
• Garbage Collection (GC): automatically reclaims heap memory for • ArrayList vs LinkedList: ArrayList has O(1) index access but O(n)
objects no longer reachable/referenced by the program, so developers insert/delete in the middle; LinkedList has O(1) insert/delete (given a node)
don't manually free memory (unlike C++). but O(n) index access.
• Why can GC still allow memory leaks? If objects remain unintentionally • HashMap vs TreeMap: HashMap offers O(1) average operations with no
referenced (e.g., stuck in a growing static collection), GC can never reclaim ordering; TreeMap keeps keys sorted, with O(log n) operations.
them even though they're no longer logically needed.
• HashSet vs TreeSet: same trade-off as HashMap/TreeMap — HashSet
is faster but unordered, TreeSet is sorted but slower.
A3. Data Types
• Primitive types: int, double, char, boolean, long, float, short, byte — A7. Multithreading Basics
store actual values directly, not objects, live on the stack (or inline in
• Thread: an independent path of execution within a program, allowing
objects).
concurrent work. Created by extending Thread or implementing Runnable.
• Wrapper classes: Integer, Double, Character, Boolean, etc. — object
• synchronized keyword: ensures only one thread can execute a
versions of primitives, needed to use them in collections (like
block/method on a given object at a time, preventing race conditions on
ArrayList<Integer>) since generics require objects.
shared data.
• Autoboxing/Unboxing: Java automatically converts between a primitive
• Deadlock: two or more threads waiting on each other's locks forever,
and its wrapper class as needed (int ↔ Integer) — convenient, but has a
unable to proceed.
small performance cost.
• Why prefer Runnable over extending Thread? Java doesn't support
• String immutability: once created, a String object's contents can never
multiple class inheritance, so implementing Runnable leaves the class free
change; operations like concatenation create a NEW String object rather
to extend something else if needed, and separates 'the task' from 'the
than modifying the original.
thread mechanism'.
• String Pool: a special memory area where Java stores String literals to
avoid creating duplicates — two identical literals (String a = "hi"; String b =
"hi";) point to the SAME pooled object.
• StringBuilder vs String: StringBuilder is mutable, making repeated
concatenation in a loop far more efficient than String (which would create
many throwaway objects).
B3. Functions
• *args: collects extra positional arguments into a tuple inside the function.
• **kwargs: collects extra keyword arguments into a dictionary inside the
function.
• Lambda: a small, anonymous, single-expression function (lambda x: x*2)
— used for short throwaway functions, e.g., as a sort key.
• Default mutable argument trap: using a mutable default (def f(x, lst=[]))
is a classic bug — the SAME list object is reused across all calls that don't
pass their own, since defaults are evaluated only once at function definition
time.
• Generators (yield): a function using 'yield' returns an iterator that
produces values lazily, one at a time, instead of building the entire result in
memory at once — crucial for processing very large or infinite sequences
efficiently.
• Decorators: a function that wraps another function to add behavior
(logging, timing, access control) without modifying the original function's
code, applied with the @decorator_name syntax.
Multiple inheritance
Not for classes Supported directly
(only interfaces)
Memory management
Garbage collected Reference counting +
(generational GC) cyclic GC
Why do interviewers ask you to compare them even if the role only uses
one? To check you understand WHY a language's design choices exist
(trade-offs), not just its syntax — e.g., knowing static typing catches certain
bugs earlier but costs verbosity/flexibility.
Rapid-Fire FAQ — JAVA (45 Questions) The compiler automatically provides a no-argument default constructor.
Q1. What is the difference between JDK, JRE, and JVM? Q20. What is garbage collection in Java?
JDK = tools to develop Java (includes JRE + compiler). JRE = environment Automatic reclamation of heap memory for objects no longer reachable by
to run Java (includes JVM + libraries). JVM = the engine that actually the program, so developers don't manually free memory.
executes bytecode. Q21. Can you force garbage collection in Java?
Q2. Why is Java called 'platform independent'? You can request it with [Link](), but it's only a suggestion to the JVM —
Java source compiles to bytecode (not native machine code), and any there's no guarantee it will run immediately or at all.
machine with a JVM can run that same bytecode regardless of underlying Q22. What is the difference between ArrayList and LinkedList?
OS/hardware. ArrayList: O(1) index access, O(n) middle insert/delete. LinkedList: O(1)
Q3. What is the difference between == and .equals() for objects? insert/delete (given a node reference), O(n) index access.
== compares object references (same memory location?); .equals() (when Q23. What is the difference between HashMap and Hashtable?
overridden) compares logical/content equality. HashMap is not synchronized (faster, not thread-safe) and allows one null
Q4. Why are Strings immutable in Java? key; Hashtable is synchronized (thread-safe, legacy) and disallows null
For security, thread-safety (safe to share across threads with no risk of keys/values.
modification), and to enable the String Pool optimization safely. Q24. What is the difference between HashMap and TreeMap?
Q5. What is the String Pool? HashMap offers O(1) average operations with no key ordering; TreeMap
A special memory area caching String literals so identical literals share the keeps keys sorted with O(log n) operations.
same object instead of creating duplicates. Q25. What is a Comparable vs Comparator in Java?
Q6. What's the difference between String, StringBuilder, and Comparable defines a class's natural ordering via compareTo()
StringBuffer? (implemented by the class itself); Comparator defines an external, custom
String is immutable. StringBuilder is mutable and NOT thread-safe (faster). ordering via compare(), usable without modifying the class.
StringBuffer is mutable AND thread-safe (synchronized, slightly slower). Q26. What is the difference between == and equals() for Strings
Q7. What is autoboxing? specifically?
Java automatically converting a primitive to its wrapper class (int to Integer) == compares references (may differ even for equal content, especially with
when needed, e.g., when adding to a generic collection. 'new String()'); .equals() compares actual character content.
Q8. Why do we need wrapper classes if we have primitives? Q27. Why override equals() and hashCode() together?
Generics and collections (like ArrayList) require objects, not primitives, so Hash-based collections use hashCode() to find a bucket and equals() to
wrapper classes let primitives be used in those contexts. confirm a match; overriding only one can break HashMap/HashSet behavior
for 'equal' objects.
Q9. What is the difference between checked and unchecked
exceptions? Q28. What is polymorphism in Java, with a quick example?
Checked exceptions must be caught or declared (enforced by the compiler); The ability for a reference of a parent type to call overridden behavior of the
unchecked (RuntimeException) exceptions aren't enforced and typically actual object's subclass at runtime, e.g., Animal a = new Dog();
indicate programming bugs. [Link]() calls Dog's version.
Q10. What does the 'finally' block guarantee? Q29. What is a package in Java?
It runs whether or not an exception was thrown or caught, used for A namespace for organizing related classes/interfaces, also controlling
guaranteed cleanup like closing resources. default (package-private) access.
Q11. What is try-with-resources? Q30. What is the 'this' keyword used for?
A try statement that automatically closes any resource implementing Refers to the current object instance, used to disambiguate fields from
AutoCloseable at the end, without needing an explicit finally block. parameters or to call another constructor in the same class.
Q12. What is the difference between an abstract class and an interface Q31. What is the 'super' keyword used for?
in Java? Refers to the immediate parent class, used to call its constructor or an
Abstract class: single inheritance, can have state/constructors. Interface: overridden method.
multiple implementation allowed, traditionally no state (Java 8+ allows Q32. What is method hiding, and how does it differ from overriding?
default/static methods). If a subclass defines a static method with the same signature as a parent's
Q13. Can an interface have a method body in modern Java? static method, it 'hides' rather than overrides it — resolved by reference
Yes, since Java 8, interfaces can have 'default' and 'static' methods with type at compile time, not object type.
actual implementations. Q33. What is a thread in Java, and how do you create one?
Q14. What is the 'final' keyword used for? An independent path of execution; created by extending Thread or
final variable = can't be reassigned; final method = can't be overridden; final (preferably) implementing Runnable and passing it to a Thread object.
class = can't be subclassed. Q34. What does the 'synchronized' keyword do?
Q15. What is the difference between static and instance methods? Ensures only one thread can execute a synchronized block/method on a
Static methods belong to the class and can be called without an object; given object at a time, preventing race conditions on shared data.
instance methods require an object and can access instance (non-static) Q35. What is a deadlock?
fields. When two or more threads are each waiting on a lock the other holds, so
Q16. Why can't static methods access instance variables directly? neither can ever proceed.
Static methods aren't tied to any specific object, so there's no 'this' object Q36. What is the difference between process and thread?
context to pull instance data from. A process has its own independent memory space; threads within the same
Q17. What is method overloading vs overriding? process share that memory space, making thread communication faster but
Overloading: same method name, different parameters, resolved at compile riskier (data races).
time. Overriding: subclass redefines a parent method with the same Q37. What is the Java Collections Framework?
signature, resolved at runtime. A unified set of interfaces (List, Set, Map, Queue) and implementations
Q18. What is a constructor, and can it be overloaded? (ArrayList, HashSet, HashMap, etc.) for storing and manipulating groups of
A special method to initialize a new object; yes, multiple constructors with objects.
different parameter lists are allowed (constructor overloading). Q38. What is generics in Java, and why use them?
Q19. What happens if you don't define any constructor in a Java A way to write classes/methods that work with any type while providing
class? compile-time type safety, e.g., List ensures only Strings can be added,
catching type errors at compile time instead of runtime.
Q39. What is type erasure?
Java generics only exist at compile time for type-checking; at runtime, the
type parameter information is erased and generic types are treated as their
raw/Object form.
Q40. What is the difference between an array and an ArrayList?
Arrays have a fixed size set at creation and can hold primitives; ArrayList is
dynamically resizable but can only hold objects (using wrapper classes for
primitives).
Q41. What is the main() method's exact required signature in Java, and
why static?
public static void main(String[] args) — it's static so the JVM can call it
without first creating an instance of the class.
Q42. What is an anonymous inner class?
A class defined and instantiated in a single expression with no name, often
used for a one-off implementation of an interface without a separate named
class.
Q43. What is the difference between a shallow copy and a deep copy in
Java?
Shallow copy ([Link]() default) copies top-level fields only, sharing
references to nested mutable objects; deep copy recursively duplicates
nested objects too, for full independence.
Q44. What is Java serialization?
Converting an object into a byte stream (implementing Serializable) so it
can be saved to disk or sent over a network, and later reconstructed
(deserialized).
Q45. Why is Java described as 'not 100% object-oriented'?
Because it has primitive data types (int, char, boolean, etc.) that are not
objects, unlike a purely object-oriented language.
Rapid-Fire FAQ — PYTHON (45 Questions) Q19. What is the GIL?
The Global Interpreter Lock in CPython — ensures only one thread
Q1. Is Python compiled or interpreted? executes Python bytecode at a time, even on multi-core CPUs, limiting true
Interpreted — though CPython actually compiles source to intermediate parallelism for CPU-bound threaded code.
bytecode (.pyc) first, which the Python Virtual Machine then interprets;
there's no separate manual compile step for the developer though. Q20. How do you achieve real parallelism in Python despite the GIL?
Use the multiprocessing module, which runs separate processes (each with
Q2. What is PEP 8? its own Python interpreter and memory space), sidestepping the single
Python's official style guide covering naming conventions, indentation, and shared GIL.
formatting for writing readable, consistent code.
Q21. Why doesn't the GIL hurt I/O-bound multithreaded programs as
Q3. What's the difference between a list and a tuple? much?
Lists are mutable (can be changed after creation); tuples are immutable. Threads release the GIL while waiting on I/O operations (network/disk), so
Tuples are also hashable (usable as dict keys), lists are not. other threads can run during that wait — the limitation mainly hits
Q4. Why would you choose a tuple over a list? CPU-bound work.
When the data shouldn't change (signals intent), when you need it as a dict Q22. What is a generator, and why use one?
key/set element (requires hashability), or for a minor performance/memory A function using 'yield' that produces values lazily, one at a time, instead of
benefit. building an entire list in memory upfront — essential for large or infinite
Q5. What's the difference between a list and a set? sequences.
Lists are ordered and allow duplicates; sets are unordered (in terms of Q23. What is the difference between yield and return?
insertion) and automatically eliminate duplicates, offering O(1) average return exits the function and sends back a single final value; yield pauses
membership checks vs O(n) for lists. the function, sends back one value, and can resume from that exact point
Q6. What is a dictionary in Python? on the next call.
A mutable collection of key-value pairs with O(1) average lookup by key, Q24. What is a decorator?
implemented internally using a hash table. A function that wraps another function to add behavior (logging, timing,
Q7. What is list comprehension, and why prefer it over a loop? access control) without modifying its original code, applied using the
A concise one-line way to build a list, e.g., [x*x for x in range(10)]. Generally @decorator_name syntax.
faster and considered more 'Pythonic' than the equivalent explicit loop with Q25. What is list slicing, and give an example.
.append(). Extracting a sub-portion of a sequence using [start:stop:step] syntax, e.g.,
Q8. What is the classic mutable default argument bug? my_list[1:4] gets elements at index 1 through 3.
Using def f(x, lst=[]): the default list is created ONCE at function definition Q26. What is the difference between deepcopy and copy in Python?
time and shared/reused across all calls that don't supply their own list, [Link]() makes a shallow copy (top-level only, shares nested
causing unexpected accumulation. references); [Link]() recursively copies nested objects too, for full
Q9. What are *args and **kwargs used for? independence.
*args collects extra positional arguments into a tuple; **kwargs collects Q27. What is the difference between is and == in Python?
extra keyword arguments into a dictionary, both letting a function accept a 'is' checks object identity (same object in memory); '==' checks value
variable number of arguments. equality (calls __eq__), which can be true even for two distinct objects with
Q10. What is a lambda function? equal content.
A small, anonymous, single-expression function, e.g., lambda x: x * 2 — Q28. What is a Python module vs a package?
typically used for short throwaway logic like a sort key. A module is a single .py file; a package is a directory of modules containing
Q11. What is the difference between a function and a method in an __init__.py file (marking it as a package).
Python? Q29. What does 'pip' do?
A function is standalone; a method is a function defined inside a class and Python's package installer, used to install/manage third-party libraries from
called on an instance, implicitly receiving 'self' as its first argument. the Python Package Index (PyPI).
Q12. What does 'self' represent in a class method? Q30. What is a virtual environment, and why use one?
A reference to the specific instance the method was called on, explicitly An isolated Python environment with its own installed packages, keeping
passed as the first parameter (unlike Java's implicit 'this'). dependencies for different projects separate and avoiding version conflicts.
Q13. What is __init__ in Python? Q31. What is exception handling syntax in Python?
The constructor method automatically called when a new object is try / except / else / finally — 'else' runs only if no exception occurred, 'finally'
instantiated, typically used to initialize instance attributes. always runs regardless.
Q14. What are dunder (magic) methods? Give two examples. Q32. Why should you avoid a bare 'except:' clause?
Special double-underscore methods that integrate a class with Python's It silently catches ALL exceptions, including typos, KeyboardInterrupt, and
built-in syntax, e.g., __str__ (controls str()/print() output) and __len__ (lets system exits, which can hide real bugs and make debugging much harder.
len() work on your object).
Q33. What is a context manager, and what syntax uses it?
Q15. How does Python handle 'private' class members? An object defining __enter__/__exit__ methods to handle setup/teardown
By convention only: a single underscore (_var) signals 'internal use'; a automatically; used with the 'with' statement, e.g., with open('file') as f:,
double underscore (__var) triggers name-mangling, but neither is truly ensuring the file closes even on error.
enforced by the language like Java's 'private'.
Q34. What's the difference between deep equality and reference
Q16. What is duck typing? equality for objects, and which does == check by default?
Python doesn't check an object's declared class before calling a method — By default, == on custom objects checks reference equality (same as 'is')
if the object has that method/attribute, the call works, regardless of its unless the class overrides __eq__ to define custom deep/value equality.
actual type.
Q35. What is the difference between a shallow and deep copy of a list
Q17. Does Python support multiple inheritance? containing nested lists?
Yes, directly — a class can inherit from multiple parent classes at once, Shallow copy creates a new outer list but the NESTED lists are still shared
unlike Java which restricts this to interfaces only. references; deep copy recursively duplicates the nested lists too, so
Q18. What is MRO (Method Resolution Order)? changes to one don't affect the other.
The order Python searches parent classes to resolve a method call when Q36. What is the difference between append() and extend() for lists?
multiple inheritance creates ambiguity, computed via the C3 linearization append() adds its argument as a SINGLE new element (even if it's a list);
algorithm. extend() adds each element of an iterable individually to the list.
Q37. What is the difference between a Python set and a frozenset?
A set is mutable; a frozenset is immutable (and therefore hashable, so it
can be used as a dict key or inside another set).
Q38. What does the walrus operator (:=) do (Python 3.8+)?
Allows assignment as part of an expression, e.g., if (n := len(data)) > 10:,
avoiding a separate assignment line before the condition.
Q39. What is monkey patching?
Dynamically modifying or extending a class/module's behavior at runtime,
without changing its original source code — possible because Python is
highly dynamic, but risky if overused.
Q40. What is the difference between a class method, a static method,
and an instance method in Python?
Instance method takes 'self' and can access instance data. Class method
takes 'cls' (via @classmethod) and works with the class itself. Static method
(@staticmethod) takes neither, behaving like a plain function namespaced
inside the class.
Q41. What is __name__ == '__main__' used for?
Checks whether a script is being run directly (not imported as a module) —
code inside that block only executes when the file is run directly.
Q42. What is a Python iterator vs an iterable?
An iterable is any object you can loop over (implements __iter__); an
iterator is the object actually produced during iteration that tracks state and
implements __next__.
Q43. What is memory management like in CPython, in one line?
Primarily reference counting (objects are freed once their reference count
hits zero), supplemented by a cyclic garbage collector for reference cycles
counting alone can't catch.
Q44. Why is string concatenation with '+' in a loop considered
inefficient in Python?
Since strings are immutable, each '+' creates a brand-new string object,
making repeated concatenation O(n²) overall; using ''.join(list_of_strings) is
far more efficient.
Q45. What is the difference between Python 2 and Python 3 that's most
commonly cited?
print became a function (print()) instead of a statement, and integer division
(/) now returns a float by default in Python 3 (use // for integer division) —
among other changes; Python 2 is also no longer officially supported.