Skip to content

Programming, OOP, Data Structures (Java & Python)

DSSSB TGT CS — Section B P1 (Rank 5). Concise MCQ-ready notes.


1. OOP Pillars

PillarMeaningExam keyword
EncapsulationBundle data + methods; hide internalsprivate fields, getters/setters
InheritanceChild reuses/extends parentextends (Java), IS-A
PolymorphismSame interface, different behavioroverloading / overriding
AbstractionShow essential, hide detailabstract class / interface
  • Compile-time polymorphism: method overloading (same name, different params)
  • Runtime polymorphism: method overriding (subclass redefines; dynamic dispatch)

Trap: Overloading ≠ overriding. Overriding needs inheritance + same signature (compatible return).


2. Class vs Object; Constructors

ClassObject
Blueprint / templateInstance of a class
Defines attributes & methodsOccupies memory at runtime

Constructor

  • Special method to initialize object
  • Same name as class (Java); no return type
  • Default constructor if none written (Java)
  • Parameterized constructor sets values
  • Constructor overloading allowed
  • Called with new (Java)

3. Java Basics

JVM & bytecode

  • Source .javacompilerbytecode .classJVM executes
  • “Write once, run anywhere” via JVM on each platform
  • JRE = JVM + libraries; JDK = JRE + development tools

Access modifiers

ModifierClassPackageSubclassWorld
privateYNNN
default (package)YYN*N
protectedYYYN
publicYYYY

*Subclass outside package: protected OK for inheritance access; default not.

static

  • Belongs to class, not instance
  • Shared among objects; callable via ClassName
  • Static methods cannot use instance (this) members directly

Interface vs Abstract class

FeatureAbstract classInterface
InstantiationNoNo
MethodsAbstract + concreteAbstract (+ default/static in modern Java)
FieldsInstance fields OKTypically public static final
InheritanceOne class extends one abstractClass can implement many interfaces
ConstructorCan haveNo (traditionally)

Exception handling

try { ... } catch (ExceptionType e) { ... } finally { ... }
  • Checked: must handle/declare (e.g., IOException)
  • Unchecked: RuntimeException and subclasses
  • throw / throws; finally almost always runs

String vs StringBuilder

StringStringBuilder
ImmutableMutable
+ creates new objectsEfficient append/modify
Thread-safe pool reuse of literalsNot synchronized (StringBuffer is)

Trap: == on Strings compares references; prefer .equals() for content.


4. Python Basics

Mutable vs Immutable

ImmutableMutable
int, float, str, tuple, frozensetlist, dict, set

Core collections

TypeOrdered*MutableDuplicatesAccess
listYYYindex
tupleYNYindex
dictY (3.7+)Ykeys uniquekey
setNYNmembership

*Insertion-ordered dicts from Python 3.7+.

Indentation

  • Blocks defined by indentation (usually 4 spaces) — syntax, not style-only

Functions

python
def f(a, b=0):
    return a + b
  • Default args, keyword args
  • *args: variable positional arguments → tuple
  • **kwargs: variable keyword arguments → dict (know the idea)

File modes

ModeMeaning
'r'Read (default)
'w'Write (truncate/create)
'a'Append
'x'Exclusive create
'b'Binary
't'Text (default)
'+'Read/write update

5. Data Structures

Array

  • Contiguous elements, same type (classic); O(1) index access; insert/delete middle O(n)

Stack (LIFO)

  • Operations: push, pop, peek/top
  • Uses: recursion call stack, undo, postfix evaluation, balanced parentheses

Queue (FIFO)

  • Enqueue rear, dequeue front
  • Variants: circular, deque, priority queue

Linked list

  • Nodes: data + pointer(s)
  • Singly / doubly / circular
  • Insert/delete at known node O(1) pointer work; search O(n)
  • No random access like arrays

Tree

  • Hierarchical; root, parent, child, leaf, depth/height
  • Binary tree: ≤ 2 children
  • BST: left < node < right (typical); search/insert average O(log n), worst O(n) if skewed

Graph

  • Vertices (nodes) + edges
  • Directed / undirected; weighted / unweighted
  • Cyclic / acyclic (DAG); connected components
  • Representations: adjacency matrix, adjacency list
  • Traversal: BFS, DFS

6. Searching

MethodIdeaTime
LinearScan one by oneO(n)
BinarySorted array; mid compareO(log n)

Trap: Binary search needs sorted data.


7. Sorting — Time Complexities

AlgorithmBestAverageWorstSpaceStable?
BubbleO(n)†O(n²)O(n²)O(1)Y
SelectionO(n²)O(n²)O(n²)O(1)N
InsertionO(n)O(n²)O(n²)O(1)Y
MergeO(n log n)O(n log n)O(n log n)O(n)Y
QuickO(n log n)O(n log n)O(n²)O(log n)*N††

† With optimized early exit; * average stack; †† typical in-place quicksort unstable.

Ideas (1-liners)

  • Bubble: adjacent swaps
  • Selection: pick min each pass
  • Insertion: build sorted prefix
  • Merge: divide & merge sorted halves
  • Quick: pivot partition

8. Recursion

  • Function calls itself with smaller input + base case
  • Uses call stack; deep recursion → stack overflow risk
  • Examples: factorial, Fibonacci, tree traversals, divide-and-conquer sorts

9. Time Complexity (Big-O) — Common Cases

ComplexityNameExample
O(1)ConstantArray index
O(log n)LogarithmicBinary search
O(n)LinearSingle loop
O(n log n)LinearithmicMerge sort
O(n²)QuadraticNested loops / bubble
O(2ⁿ)ExponentialNaive subset / Fib recursion
O(n!)FactorialAll permutations

Order (slow → fast growth): O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ) < O(n!)

Trap: Big-O is upper bound asymptotic; ignore constants & lower terms for MCQs unless asked precisely.


Quick traps checklist

  1. Encapsulation hides; abstraction simplifies view.
  2. JVM runs bytecode; JDK includes compiler tools.
  3. static → class-level.
  4. Interface: multiple inheritance of type; abstract class: single extend.
  5. String immutable; StringBuilder mutable.
  6. list mutable; tuple immutable; set unique unordered.
  7. Stack LIFO; Queue FIFO.
  8. BST left < root < right.
  9. Binary search needs sorted input.
  10. Quick worst O(n²); Merge always O(n log n).