Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Programming paradigms

Programming paradigms: imperative/procedural, object-oriented, functional, declarative, event-driven, concurrent, and how Java supports and blends them.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Programming paradigms are the fundamental styles of thinking and structuring code to solve problems. In real projects, engineers pick a paradigm (or a blend) that best fits requirements: e.g., object-oriented design for maintainable systems, functional style for safe data processing, event-driven for GUIs or servers, and concurrent style for performance.

Key ideas

  • Definition: An imperative paradigm describes computation as a sequence of commands that change program state (the values stored in variables and objects) by assignments and control flow (if, loops). Core idea: tell the computer “how to do it” step by step.

  • Definition: A procedural paradigm is an imperative style that groups sequences of statements into procedures or methods (with parameters and return values) to achieve modularity and reuse. Assumption: state is passed via parameters or maintained in local/module scope (avoid globals); control is top-down.

  • Definition: An object-oriented (OO) paradigm organizes code around objects that bundle state (fields) and behavior (methods). The four pillars are:

    • Encapsulation: hiding internal state behind a well-defined interface.
    • Abstraction: exposing only essential features.
    • Inheritance: forming new classes from existing ones to reuse behavior.
    • Polymorphism: one interface, many implementations (dynamic method dispatch). Exact statement (OO substitution principle): If S is a subtype of T, then objects of type T may be replaced with objects of type S without breaking correctness of the program that uses T’s interface (Liskov Substitution Principle), assuming clients depend only on the interface contract.
  • Definition: A functional paradigm models computation as evaluation of pure functions (no side effects) and emphasizes immutability (data not changed after creation) and referential transparency (an expression can be replaced with its value without changing program behavior). Assumption: state changes are represented as new values, not mutations.

  • Definition: A declarative paradigm specifies “what to compute” rather than “how to compute it,” leaving control strategy to the runtime (examples: SQL, regular expressions, and many stream operations). In Java, parts of the standard library (Streams API) allow declarative pipelines. Stream intermediate operations are lazy and execute only when a terminal operation is invoked.

  • Definition: A logic paradigm expresses computation as logical relations and uses automated inference (e.g., Prolog). Java does not natively implement logic programming, but libraries and interop can simulate it. In exams, state: Java is multi-paradigm but not a native logic language.

  • Definition: An event-driven paradigm structures programs around events (user actions, messages, signals). Components register listeners (callbacks) that react when events occur. Common in GUIs, servers, and frameworks.

  • Definition: A concurrent paradigm allows multiple units of computation to make progress “at the same time,” potentially on multiple cores/CPUs. In Java, this includes threads, executors, and synchronization tools. Assumption: correctness must consider race conditions, visibility, and ordering. Note: Concurrency is about dealing with many tasks at once (structuring interaction and progress), while parallelism is about executing multiple tasks simultaneously on hardware; parallelism implies concurrency, but not vice versa.

  • Definition: A reactive style is an event-driven, asynchronous, non-blocking approach focusing on data streams and propagation of change. In Java, reactive libraries (e.g., Reactive Streams implementations) support this, but it is beyond the core exam scope; mention only as an extension of event-driven and concurrent ideas.

  • Blending in Java: Java is a multi-paradigm language. Typical blends:

    • Imperative + OO: most application logic (loops manipulating object state).
    • OO + Functional: lambdas and Streams for collection processing.
    • OO + Event-driven: listeners in GUI/web frameworks.
    • OO + Concurrency: threads/executors with synchronized objects.
  • Exact principles often asked in exams:

    • Law (referential transparency): For a pure function f and input x, evaluating f(x) always yields the same result and may be replaced by that result without changing program behavior. Assumptions: no side effects, no external state, and deterministic execution.
    • Invariance under encapsulation: Changes to private implementation do not break clients if the public contract remains the same. Assumption: clients use only the public API and respect documented pre/post-conditions.
    • Liskov Substitution Principle (contract rules): Subtypes must not strengthen preconditions nor weaken postconditions of overridden methods; they must preserve invariants and only throw exceptions compatible with the base contract.
  • How paradigms change design:

    1. Start with the problem statement.
    2. If it is data-centric with entities and behaviors: pick OO (classes represent entities).
    3. If it is data transformation over collections: pick functional/declarative (pipelines).
    4. If it is sequence-heavy with simple steps: pick imperative/procedural.
    5. If it is driven by inputs over time (clicks, messages): pick event-driven.
    6. If speed/throughput is key: add concurrency carefully (threads/executors).
  • Diagram 1 to draw (Paradigm map): Draw a horizontal line labeled “How vs What”. On left, write Imperative/Procedural ("How"). On right, write Declarative/Functional ("What"). Above the line midway, place OO as an umbrella that can lean left (imperative methods) or right (functional methods via lambdas). Below, draw Event-driven and Concurrent as orthogonal concerns with arrows pointing to OO (indicating combination). Label each box with 2–3 keywords (e.g., Functional: purity, immutability; Event-driven: listener, callback).

  • Diagram 2 to draw (Event flow): Left box “Event Source”, arrow to “Event Queue”, arrow to “Event Loop/Dispatcher”, arrows to multiple “Listeners/Handlers”. Label arrows as “onClick(), onMessage(), etc.” Show that handlers update “Model” (another box), and UI/View subscribes to model changes. This explains event-driven flow in Java GUIs/servers.

  • Where Java fits in the subject map (don’t re-teach; just reference): OO features are covered in “Object-oriented concepts”, “Classes, objects and methods in Java”, “Inheritance in Java”, “Interfaces in Java”. Functional features (lambdas, streams) appear in “Iterators and generic classes in Java” and are used here declaratively. Concurrency is covered in “Multithreading in Java”.

Formulas

For a programming topic, learn the syntax patterns:

  • class ClassName { fields; constructors; methods } — Define a class (OO encapsulation). Use in OO paradigm.
  • interface I { abstract methods; default methods; static methods } — Define an interface (polymorphism). Use for contracts.
  • new ClassName(args) — Object creation (state + behavior).
  • Type var = expression; — Variable declaration (imperative state).
  • if (cond) { … } else { … } — Conditional control flow (imperative).
  • for (init; cond; step) { … } — Classic for-loop (imperative/procedural).
  • for (Type x : iterable) { … } — Enhanced for-loop (imperative over collections).
  • (params) -> expression — Lambda (functional). Example: (x) -> x * x.
  • (params) -> { statements; } — Lambda with block.
  • Type::methodName — Method reference (functional shorthand). Example: System.out::println.
  • stream.filter(p).map(f).reduce(id, op) — Declarative Stream pipeline (functional/declarative). p is predicate, f is mapper, op is associative combiner, id is identity element. Note: reduce without an identity returns Optional<T>.
  • Optional<T> usage: Optional.ofNullable(v).orElse(default) — Declarative null-handling.
  • try (Resource r = open()) { … } — Structured resource management (declarative control of lifetimes).
  • new Thread(runnable).start() — Basic concurrency (don’t use for large-scale in production; prefer executors).
  • ExecutorService exec = Executors.newFixedThreadPool(n); — Concurrency with a pool.
  • addListener(handler) / removeListener(handler) — Event-driven pattern (e.g., GUI listeners).

Worked examples

Example 1: Imperative/Procedural style — Sum of even numbers up to N Complete program:

import java.util.*;

public class SumEvenImperative {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int sum = 0;                     // state mutated in a loop (imperative)
        for (int i = 1; i <= N; i++) {   // explicit control flow
            if (i % 2 == 0) {
                sum += i;               // assignment updates state
            }
        }
        System.out.println(sum);
        sc.close();
    }
}

Sample input:

10

Exact output:

30

Example 2: Object-Oriented style — Simple BankAccount with encapsulation Complete program:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

class BankAccount {
    private final String owner;            // encapsulated state
    private BigDecimal balance;            // mutable field with invariants

    public BankAccount(String owner, BigDecimal initial) {
        if (owner == null || owner.isEmpty()) throw new IllegalArgumentException("Owner required");
        if (initial == null || initial.compareTo(BigDecimal.ZERO) < 0) throw new IllegalArgumentException("Initial >= 0");
        this.owner = owner;
        this.balance = initial.setScale(2, RoundingMode.HALF_UP);
    }

    public String getOwner() { return owner; }

    public BigDecimal getBalance() { return balance; }

    public void deposit(BigDecimal amount) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) throw new IllegalArgumentException("Deposit > 0");
        balance = balance.add(amount).setScale(2, RoundingMode.HALF_UP);
    }

    public void withdraw(BigDecimal amount) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) throw new IllegalArgumentException("Withdraw > 0");
        if (amount.compareTo(balance) > 0) throw new IllegalArgumentException("Insufficient funds");
        balance = balance.subtract(amount).setScale(2, RoundingMode.HALF_UP);
    }

    @Override
    public String toString() {
        return owner + ": Rs " + balance.toPlainString();
    }
}

public class OOAccountDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine().trim();
        BigDecimal initial = new BigDecimal(sc.nextLine().trim());
        BigDecimal withdrawAmt = new BigDecimal(sc.nextLine().trim());
        BigDecimal depositAmt = new BigDecimal(sc.nextLine().trim());
        BankAccount acc = new BankAccount(name, initial);
        acc.withdraw(withdrawAmt);
        System.out.println("After withdrawal: " + acc);
        acc.deposit(depositAmt);
        System.out.println("After deposit: " + acc);
        sc.close();
    }
}

Sample input:

Ravi
1000.00
200.00
500.00

Exact output:

After withdrawal: Ravi: Rs 800.00
After deposit: Ravi: Rs 1300.00

Notes: This demonstrates OO encapsulation (private fields), invariants (non-negative balance), and behavior methods exposed by a class.

Example 3: Functional/Declarative style — Filter, map, and reduce with Streams Complete program:

import java.util.*;
import java.util.stream.*;

public class FunctionalStreamDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        List<Integer> nums = Arrays.stream(line.trim().split("\\s+"))
                .filter(s -> !s.isEmpty())
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        List<Integer> evens = nums.stream()
                .filter(x -> x % 2 == 0)               // predicate: keep even
                .collect(Collectors.toList());

        List<Integer> squares = evens.stream()
                .map(x -> x * x)                        // mapper: square
                .collect(Collectors.toList());

        int sum = squares.stream()
                .reduce(0, Integer::sum);               // reduce: sum with identity 0

        System.out.println("Evens: " + evens);
        System.out.println("Squares: " + squares);
        System.out.println("Sum: " + sum);
        sc.close();
    }
}

Sample input:

1 2 3 4 5 6

Exact output:

Evens: [2, 4, 6]
Squares: [4, 16, 36]
Sum: 56

Notes: This is declarative because we specify what to keep/map/reduce, not how to loop. It is functional because each lambda is a pure function with no side effects.

Common mistakes

  • Side effects inside Stream operations: modifying external lists or printing inside map/filter. This breaks functional purity and can cause unexpected results. Keep stream lambdas pure; do side effects only in terminal operations if needed (forEach).
  • Creating parallel streams blindly: collection.parallelStream() without checking if operations are associative and stateless. This can give wrong answers or low performance.
  • Mutating collections while streaming/iterating: leads to ConcurrentModificationException. Use collectors to build new collections; avoid mutation during traversal.
  • Overusing inheritance to reuse code (wrong paradigm choice): prefer composition; use interfaces for polymorphism.
  • Treating event-driven handlers as mini-main methods: forgetting thread rules (e.g., GUI updates must happen on the event-dispatch thread). Know the event loop model of the framework you use.
  • Procedural thinking in OO APIs: making “God classes” that do everything; not leveraging polymorphism and interfaces for variability.
  • Expecting functional features to enforce immutability automatically: in Java, List etc. are mutable by default; use unmodifiable wrappers or records/immutable patterns explicitly.

For your exam

  • Short notes: “OO vs Functional”, “Declarative programming in Java Streams”, “Event-driven programming model”. Include benefits, typical use cases, and one code snippet.
  • Diagram questions: Draw and label the Paradigm map (how vs what) and Event flow diagram as described above; explain each arrow/box briefly.
  • Programs:
    • Imperative task (loops, conditionals) — show clear state and control flow.
    • OO task (design a class with fields/methods, enforce invariants) — show encapsulation and method-based behavior.
    • Functional task (streams: filter–map–reduce) — show pure lambdas and correct collectors. Provide sample input and exact output; handle basic validation where reasonable.
  • Reasoning/derivation style: Explain why a stream reduction requires an associative combiner and identity to be correct (especially for parallel streams). State: operation op must be associative and identity id must satisfy id op x = x op id = x.
  • Comparisons: “When to use OO vs Functional in Java?” Answer with criteria: mutable domain models vs transformation pipelines; need for polymorphism vs need for concise, side-effect-free transforms; runtime framework requirements (event-driven GUIs/servers).

Quick check

  1. What is referential transparency, and why is it useful in Java Streams?
  2. Name two differences between imperative and declarative styles with one Java example each.
  3. In event-driven programming, what is a listener and how does it relate to an event loop?

Answers: 1) An expression can be replaced by its value without changing program behavior; ensures predictability and enables safe reordering/caching in stream pipelines. 2) Imperative says how (e.g., for loop summing numbers), declarative says what (e.g., stream().map(...).reduce(...)); imperative mutates state, declarative avoids explicit mutation. 3) A listener is a callback object/function registered to be invoked when an event occurs; the event loop/dispatcher pulls events from a queue and calls the appropriate listeners.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?