Advanced Programming Concepts MCQs for the NSCT

By the NSCT Exam Editorial Team · Updated 2026-11-24 · Facts checked against official sources on 2026-11-24

Advanced programming concepts are the features that let you write code once and reuse it safely across types and behaviours: generics in Java, templates in C++, lambdas and higher-order functions, and iterators and generators. It is topic 13 of the 16 in the Programming (C++/Java/Python) area, which carries 10% of the NSCT according to HEC's Areas of Competencies. Candidates averaged 47.8% accuracy in this area in 2026, per the HEC NSCT report.

Most questions are short output traces, so make sure you are comfortable with functions and methods first. Closures and decorators build directly on them.

Generics

Generics let a class or method work with a type parameter, so the compiler can check types for you. In Java, List<String> rejects an Integer at compile time, and get() returns a String with no cast.

static <T extends Comparable<T>> T largest(List<T> xs) {
    T best = xs.get(0);
    for (T x : xs) if (x.compareTo(best) > 0) best = x;
    return best;
}

The bound T extends Comparable<T> is what allows the call to compareTo. Java implements generics by type erasure: the type arguments are checked and then removed, so at run time List<String> and List<Integer> share one class. That is why new T() and List<int> are illegal.

Rule Meaning
Invariance List<String> is not a List<Object>
? extends Number Safe to read as Number; cannot add (except null)
? super Integer Safe to add an Integer; reads give Object

Exam angle: a line like List<Object> objs = new ArrayList<String>(); does not compile. Expect at least one "which line fails?" question built on invariance.

Lambdas

A lambda is an anonymous function written inline. Each language has its own syntax:

Language Syntax Notes
Python lambda a, b: a + b One expression only; no return
Java (a, b) -> a + b Must target a functional interface (one abstract method)
C++ [&](int a, int b) { return a + b; } Capture list: [=] copies, [&] references
JavaScript (a, b) => a + b Arrow function

Lambdas are usually passed to higher-order functions, which take or return functions:

students = [("Hira", 82), ("Usman", 74), ("Zara", 91)]
print(sorted(students, key=lambda s: s[1], reverse=True))
# [('Zara', 91), ('Hira', 82), ('Usman', 74)]

A closure is an inner function that keeps access to its enclosing function's variables after that function returns. A decorator such as @timer is shorthand for f = timer(f).

Exam angle: closures capture variables, not values. [lambda: i for i in range(3)] gives three functions that all return 2.

Templates

A C++ template is a blueprint from which the compiler generates a separate function or class for each type it is used with:

template <typename T>
T maxOf(T a, T b) { return a > b ? a : b; }
// maxOf(3, 7) -> maxOf<int>, maxOf(2.5, 1.5) -> maxOf<double>

Templates and Java generics solve the same problem in different ways. Textbooks contrast them like this:

C++ templates Java generics
When resolved Compile time, code generated per type Compile time, then erased
Primitive types Allowed (maxOf<int>) Not allowed (use Integer)
Type checked When instantiated When declared, using bounds

Exam angle: maxOf(3, 2.5) does not compile, because T is deduced as int from one argument and double from the other. maxOf<double>(3, 2.5) fixes it.

Iterators

An iterator hands out the items of a collection one at a time. Python's protocol is __iter__ plus __next__, which raises StopIteration at the end. Java's is hasNext() plus next(). A generator is the easiest way to write one in Python:

def countdown(n):
    while n > 0:
        yield n
        n -= 1

print(list(countdown(3)))   # [3, 2, 1]

Generators are lazy: calling countdown(3) runs nothing until values are requested.

Exam angle: an iterator can be consumed once. After sum(it), a second sum(it) returns 0. In Java, removing from a list inside a for-each loop throws ConcurrentModificationException.

Common traps

Worked examples

1. Understanding. Is Python's range(3) an iterator? Answer: No, it is an iterable. It has no __next__ method, and you can loop over the same range many times. iter(range(3)) returns a separate iterator object that can be used once.

2. Application. What does this print?

def pairs():
    yield from zip("ab", [1, 2])
print(dict(pairs()))

Answer: {'a': 1, 'b': 2}. yield from passes on each tuple that zip produces, and dict() turns the key-value pairs into a dictionary.

3. Analysis. In JavaScript, [10, 1, 2].sort() returns [1, 10, 2]. Why, and what is the fix? Answer: with no comparator, sort() converts elements to strings and compares them as text, and "10" sorts before "2". Passing a lambda, .sort((a, b) => a - b), compares numerically and returns [1, 2, 10].

Practise

The quiz below has 100 questions on advanced programming concepts, filterable by tier and difficulty.

Practise: 100 questions

Interactive quiz loading. The first 10 questions are shown below.

  1. What is the main benefit of using generics, such as List<String> in Java, instead of a raw List of Object?

    1. Elements are stored more compactly in memory
    2. The compiler checks element types, so casts are not needed when reading
    3. The list becomes thread-safe automatically
    4. A class can inherit from several parent classes
    Show answer

    Answer: B. The compiler checks element types, so casts are not needed when reading

    Generics give compile-time type safety: adding an Integer to a List<String> is rejected by the compiler, and get() already returns String, so no cast is needed. They do not change memory layout, add thread safety or allow multiple class inheritance.

  2. Which of these is a valid Python lambda that doubles its argument?

    1. lambda x: x * 2
    2. lambda x: return x * 2
    3. lambda(x) => x * 2
    4. def lambda(x): x * 2
    Show answer

    Answer: A. lambda x: x * 2

    A Python lambda is lambda parameters: expression. Its body must be a single expression, so return is not allowed. The => arrow is JavaScript or C# syntax, and lambda is a reserved keyword, so it cannot be a function name.

  3. In Java, what happens to the type argument of a generic such as List<String> at run time?

    1. A separate class is generated for each type argument, as with C++ templates
    2. It is kept and checked on every add() call
    3. It is converted to the wrapper class Object[] and copied
    4. It is erased, so List<String> and List<Integer> share the same runtime class
    Show answer

    Answer: D. It is erased, so List<String> and List<Integer> share the same runtime class

    Java implements generics by type erasure: the compiler checks types and inserts casts, then removes the type arguments. At run time both lists are plain ArrayList objects, so new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass() is true. Per-type code generation is how C++ templates work.

  4. When is the code for a C++ function template such as template <typename T> T maxOf(T a, T b) actually generated?

    1. At run time, when the function is first called
    2. Once, using a single version that works on void pointers
    3. Only when the program is linked, never by the compiler
    4. At compile time, once for each distinct type the template is used with
    Show answer

    Answer: D. At compile time, once for each distinct type the template is used with

    A template is a blueprint. When the compiler sees maxOf(3, 7) and maxOf(2.5, 1.5), it instantiates maxOf<int> and maxOf<double> as separate functions at compile time. Nothing is generated at run time, and there is no single void-pointer version.

  5. Which pair of special methods makes a Python object an iterator?

    1. __getitem__ and __len__
    2. hasNext and next
    3. __iter__ and __next__
    4. __enter__ and __exit__
    Show answer

    Answer: C. __iter__ and __next__

    Python's iterator protocol needs __iter__ (return the iterator, usually self) and __next__ (return the next item or raise StopIteration). __enter__/__exit__ make a context manager, and hasNext/next is Java's Iterator interface.

  6. Which two methods must every Java Iterator<E> provide (apart from the optional remove())?

    1. hasNext() and next()
    2. begin() and end()
    3. __iter__() and __next__()
    4. first() and last()
    Show answer

    Answer: A. hasNext() and next()

    java.util.Iterator declares hasNext(), next() and a default remove(). A for-each loop over a collection calls these behind the scenes. begin()/end() are C++ container functions and __iter__/__next__ are Python's protocol.

  7. How does a Python for loop know that an iterator has no more items?

    1. __next__ returns None
    2. __next__ raises IndexError
    3. __next__ raises StopIteration
    4. The loop checks len() before each step
    Show answer

    Answer: C. __next__ raises StopIteration

    The for loop keeps calling next() and stops when StopIteration is raised. Returning None would just produce a None item. IndexError belongs to the older __getitem__ sequence protocol, and iterators need not have a length at all.

  8. What is a higher-order function?

    1. A function that takes a function as an argument or returns a function
    2. A function declared inside a class
    3. A function with more than three parameters
    4. A recursive function that calls itself
    Show answer

    Answer: A. A function that takes a function as an argument or returns a function

    Higher-order functions treat functions as values. map, filter, sorted(key=...) and Java's Stream.map all accept a function; a decorator both accepts and returns one. Being a method, having many parameters or being recursive has nothing to do with it.

  9. What is a closure?

    1. A function that closes all open files when it ends
    2. A function that cannot be overridden in a subclass
    3. A block of code that runs when the program exits
    4. An inner function that keeps access to variables of its enclosing function after that function has returned
    Show answer

    Answer: D. An inner function that keeps access to variables of its enclosing function after that function has returned

    When an inner function refers to a variable of its enclosing function, the variable is captured. The inner function can still read (and, with nonlocal, change) it after the outer call has finished. Counter factories and decorators rely on this.

  10. What happens when you call a Python function whose body contains yield?

    1. It runs the whole body at once and returns a list
    2. It raises a SyntaxError unless the call is inside a for loop
    3. It runs the body until the first yield and returns that value
    4. It returns a generator object; the body runs only as values are requested
    Show answer

    Answer: D. It returns a generator object; the body runs only as values are requested

    Any function containing yield is a generator function. Calling it creates a generator object without executing any of the body. Each next() call runs the body up to the next yield and pauses there, which is why generators are lazy.

FAQs

Are Java generics and C++ templates the same thing?

No. Both give type-safe reusable code, but C++ generates separate code for each type at compile time, while Java checks the types and then erases them, leaving one shared class. So C++ templates accept primitive types and Java generics do not. Java also cannot create a new T().

When should I use a lambda instead of a named function?

Use a lambda for a short, one-off function passed straight to another function, such as a sort key or a map callback. If the logic needs several statements, a name or a docstring, write a normal function. Python lambdas are limited to one expression, so longer logic must be a def.

What is the difference between an iterable and an iterator?

An iterable can produce an iterator; lists, strings, ranges and dictionaries are iterables. An iterator holds the current position and returns the next item each time next() is called, until it is exhausted. A for loop calls iter() on the iterable for you, which is why lists can be looped over repeatedly.

Do I need to know C++20 concepts or Java streams for the NSCT?

HEC's topic list names this area but does not go into that level of detail. Make sure you are solid on generics, lambdas, templates and iterators first. Streams are a natural extension, since stream().filter(...).map(...) is just higher-order functions and lambdas used together.

Next step

Continue to Concurrency & Parallelism MCQs, where lambdas reappear as thread tasks. Revisit the Programming MCQs hub or test yourself in an NSCT mock test.