wayground logo

Free Printable Worksheets

Font size

S
M
L
XL
Worksheets

SE1 lý thuyết

Total questions: 150

Worksheet time: 1hrs 15mins

Name
Class
Date
1.

Which of the following is something an abstract class CANNOT do?

a)

Contain abstract methods

b)

Contain concrete methods

c)

Be instantiated directly using new

d)

Have a constructor

2.

Which statement is true about an abstract method?

a)

It cannot be overridden

b)

It must be declared final

c)

It has no method body

d)

It must have a full method body

3.

What can an interface NOT contain?

a)

Method signatures

b)

Constructors

c)

public static final constants

d)

Abstract methods

4.

How many interfaces can a class implement in Java?

a)

Maximum 2

b)

Exactly 1

c)

Unlimited number

d)

0 or 1

5.

Which keyword is used to inherit from an abstract class?

a)

override

b)

implements

c)

extends

d)

super

6.

Which keyword is used to implement an interface?

a)

override

b)

extends

c)

inherit

d)

implements

7.

According to the pre-condition rule, a subclass must:

a)

Have stricter input requirements

b)

Have no constraints

c)

Reject more inputs than the superclass

d)

Have weaker or equal input requirements

8.

According to the post-condition rule, a subclass must:

a)

Return a wider range of outputs

b)

Return weaker guarantees

c)

Return stronger or equal guarantees

d)

Not change the output

9.

Which of the following is true about polymorphism?

a)

It only works with interfaces

b)

It requires final methods

c)

It increases reuse and maintainability

d)

It is static binding

10.

When should you use an abstract class?

a)

When unrelated classes need the same behavior

b)

When classes share common characteristics (IS-A)

c)

When multiple inheritance of classes is needed

d)

When no shared logic is needed

11.

Which statement best distinguishes an abstract class from an interface in an object‑oriented language?

a)

Interfaces can have state and constructors; abstract classes cannot

b)

Abstract classes allow constructors and fields; interfaces do not

c)

Interfaces support inheritance of implementation; abstract classes never do

d)

Abstract classes only declare method signatures; interfaces provide bodies

12.

When should you prefer an abstract class over an interface?

a)

When classes share common properties and behavior

b)

When unrelated classes follow the same contract

c)

When you need multiple inheritance of implementations

d)

When no shared logic exists across classes

13.

When is an interface the better choice?

a)

When classes share state and concrete methods

b)

When subclassing is required to reuse implementation

c)

When you must restrict instantiation with constructors

d)

When unrelated classes must expose the same behavior

14.

According to the pre‑condition rule for method overriding, a subclass must:

a)

Have no constraints on input at all

b)

Accept weaker or equal input restrictions

c)

Reject a broader set of inputs than the superclass

d)

Demand stricter input requirements than the superclass

15.

According to the post‑condition rule for method overriding, a subclass must:

a)

Provide stronger or equal output guarantees

b)

Return weaker guarantees than the superclass

c)

Return a wider range of outputs than before

d)

Avoid changing the method’s observable effects

16.

What is polymorphism in object‑oriented programming?

a)

Sharing fields across subclasses automatically

b)

Static binding of method calls at compile time

c)

A single class owning many unrelated interfaces

d)

Different objects respond differently to the same method call

17.

Why do interfaces enable polymorphism effectively?

a)

Multiple classes can implement the same contract type

b)

They require final methods for consistent behavior

c)

They enforce constructors for uniform instantiation

d)

They prevent method overriding across implementations

18.

Why can’t an abstract class be instantiated directly?

a)

It must be declared final to be used

b)

It lacks any fields or constructors by design

c)

It contains abstract methods without implementation

d)

It always requires multiple inheritance

19.

Choose the correct declaration of an abstract class with one abstract method makeSound().

a)

abstract class Animal { void makeSound() {} }

b)

class Animal { abstract void makeSound() {} }

c)

interface Animal { abstract void makeSound(); }

d)

abstract class Animal { abstract void makeSound(); }

20.

Select the correct interface declaration with a single method fly().

a)

interface Flyable { void fly(); }

b)

abstract interface Flyable { void fly() {} }

c)

class Flyable { void fly(); }

d)

interface Flyable { final void fly(); }

21.

Which statement about polymorphism is false?

a)

It increases reuse and maintainability of code

b)

It only works when using interfaces

c)

Method calls can dispatch to different implementations

d)

Different types can be treated uniformly by a common type

22.

Identify the correct application of the pre‑condition rule when overriding validate(input).

a)

Subclass accepts more input cases than superclass

b)

Subclass requires stricter input than superclass

c)

Subclass rejects all inputs superclass accepts

d)

Subclass ignores input and throws an error

23.

Identify the correct application of the post‑condition rule when overriding compute().

a)

Subclass removes all guarantees on outputs

b)

Subclass returns unrelated data type arbitrarily

c)

Subclass returns guarantees at least as strong

d)

Subclass weakens output guarantees overall

24.

Which situation most strongly suggests using an interface over an abstract class?

a)

Airplane, Bird, and Drone must all be flyable

b)

Cat and Dog share fields and a base eat() method

c)

Shapes share area() logic and state

d)

A family of sensors needs common calibration code

25.

Select the best reason to declare a method abstract in a base class.

a)

You need subclasses to provide specific implementations

b)

You need to store shared state for all instances

c)

You must allow direct instantiation of the base

d)

You want to prevent overriding in subclasses

26.

Which option correctly describes method overriding?

a)

Superclass replaces a method of its subclass at runtime

b)

Subclass adds a new unrelated method to the type

c)

Subclass hides a field with the same name as superclass

d)

Subclass provides its own implementation for an inherited signature

27.

In an abstract class Animal with abstract makeSound() and concrete eat(), what must subclasses Dog and Cat do regarding makeSound()?

a)

Override eat() instead of makeSound()

b)

Use interface default method for makeSound()

c)

Provide concrete implementations of makeSound()

d)

Declare makeSound() as final and unused

28.

Given: Animal a = new Dog("Rex"); a.makeSound(); a.eat(); Which concept allows a to call Dog’s makeSound() while typed as Animal?

a)

Polymorphism via dynamic dispatch

b)

Encapsulation through private fields

c)

Inheritance through constructor chaining

d)

Abstraction using abstract data types

29.

You create an interface Flyable with method fly(). Classes Bird, Airplane, Superman implement it. What must each class provide at minimum?

a)

A protected fly() with no body

b)

An abstract fly() declaration

c)

A concrete fly() implementation

d)

A static fly() utility method

30.

Which statement best describes interface implementation messages for Bird, Airplane, Superman?

a)

All must be identical across classes

b)

Each should differ while satisfying Flyable

c)

Messages depend on abstract class Animal

d)

Only Bird needs a unique message

31.

Given interface Drawable { void draw(); } and classes Circle, Square, Triangle implement it. What collection type enables polymorphic iteration calling draw()?

a)

Map from Class to Method

b)

ArrayList of String names

c)

Array of Object references

d)

Drawable[] array of shapes

32.

In a loop over Drawable[] shapes, what happens when draw() is called on each element?

a)

The concrete class’s draw() executes

b)

Only Circle implements draw() correctly

c)

The interface’s default draw() runs

d)

A runtime error occurs for interfaces

33.

Pre-condition in method add(int a) ensures a > 2. What is the primary purpose of this pre-condition?

a)

Describe output formatting rules

b)

Optimize memory allocation strategy

c)

Prevent overriding in subclasses entirely

d)

Guarantee caller meets input constraints

34.

Post-condition in add returns a + 5 with result > 7. What does the post-condition guarantee?

a)

The object state resets after execution

b)

The parameter becomes immutable forever

c)

The returned value satisfies a constraint

d)

The method will never throw exceptions

35.

A subclass BetterCalculator accepts weaker input (a > 0) and stronger output (result > 10). Which correctness principle is demonstrated?

a)

Liskov substitution with contract strengthening

b)

Open/Closed principle violating inheritance

c)

Singleton pattern ensuring one instance

d)

Dependency inversion through interfaces

36.

Interfaces Runnable { void run(); } and Jumpable { void jump(); }. A class Athlete implements both. What must Athlete include?

a)

A single method combining both actions

b)

Protected constructors for each interface

c)

Two abstract method stubs only

d)

Concrete run() and jump() methods

37.

Which statement is TRUE about checked exceptions?

a)

They indicate programming logic errors

b)

They inherit from RuntimeException hierarchy

c)

They must be handled or declared using throws

d)

They occur only at runtime

38.

Which of the following is an unchecked exception?

a)

IOException in file handling

b)

FileNotFoundException thrown by IO

c)

ClassNotFoundException from ClassLoader

d)

NullPointerException due to null dereference

39.

Unchecked exceptions are subclasses of which type?

a)

RuntimeException specific hierarchy

b)

IOException in IO package

c)

Throwable root class of errors

d)

Exception in general hierarchy

40.

When designing an abstract Animal, which member is valid in an abstract class but not in an interface (pre-Java 8)?

a)

Multiple inheritance of implementation

b)

Private instance fields with state

c)

Abstract methods without bodies

d)

Public constants defined inline

41.

A method overriding add(int a) in BetterCalculator changes pre-condition from a > 2 to a > 0. Which risk must be avoided to preserve substitutability?

a)

Ignoring super.add call in implementation

b)

Using more parameters than superclass

c)

Throwing fewer exceptions than superclass

d)

Making output constraint weaker than superclass

42.

Which statement is TRUE about checked exceptions?

a)

They represent programming logic errors

b)

They must be handled or declared using throws

c)

They inherit from RuntimeException

d)

They occur only at runtime

43.

Which of the following is an unchecked exception?

a)

NullPointerException

b)

ClassNotFoundException

c)

IOException

d)

FileNotFoundException

44.

Unchecked exceptions are subclasses of:

a)

Exception

b)

Throwable

c)

RuntimeException

d)

IOException

45.

Which action does the throw keyword perform?

a)

Declares that a method might throw an exception

b)

Catches an exception

c)

Throws an exception object inside a method

d)

Converts checked exception to unchecked exception

46.

Which action does the throws keyword perform?

a)

Declares that the method may throw an exception

b)

Immediately terminates the method

c)

Logs an exception

d)

Creates an exception object

47.

A compile-time error occurs during:

a)

Logical operations

b)

Syntax and type checking

c)

JVM interpretation

d)

Program execution

48.

A runtime error occurs during:

a)

Compiling

b)

Writing code

c)

Program execution

d)

IDE formatting

49.

Which exception category typically represents external/environment errors?

a)

Logic exceptions

b)

Unchecked

c)

RuntimeException

d)

Checked

50.

What is “masking” in exception handling?

a)

Reflecting the original error

b)

Logging the error then rethrowing

c)

Hiding an exception and throwing a more meaningful one

d)

Printing the stack trace only

51.

What does “reflecting” an exception mean?

a)

Logging and swallowing the error

b)

Re-throwing the original exception to the caller

c)

Converting the exception into another exception

d)

Preventing error propagation

52.

What is the difference between checked and unchecked exceptions? Provide a concise explanation.

a)

Checked must be handled at compile time; unchecked occur at runtime

b)

Checked occur at runtime; unchecked must be declared

c)

Checked are logic errors; unchecked are syntax errors

d)

Checked are from RuntimeException; unchecked are from Exception

53.

Select two examples of checked exceptions.

a)

IOException and FileNotFoundException

b)

NullPointerException and ArithmeticException

c)

OutOfMemoryError and StackOverflowError

d)

IllegalArgumentException and NumberFormatException

54.

Select two examples of unchecked exceptions.

a)

IOException and FileNotFoundException

b)

NullPointerException and ArithmeticException

c)

ClassNotFoundException and SQLException

d)

EOFException and InterruptedException

55.

What is the primary purpose of the throw keyword in a method body?

a)

Declare potential exceptions to callers

b)

Create an exception class

c)

Convert checked to unchecked exceptions

d)

Throw a specific exception instance

56.

What is the primary purpose of the throws keyword in a method signature?

a)

Handle exceptions internally

b)

Declare that the method may throw exceptions

c)

Log exceptions to a file

d)

Terminate execution on error

57.

Which action best describes logging an exception?

a)

Terminating the JVM on error

b)

Transforming it into a custom exception

c)

Recording the error to file or console

d)

Suppressing the stack trace

58.

Which scenario most clearly involves exception masking?

a)

Ignoring the catch block entirely

b)

Catching and rethrowing the same exception

c)

Printing stack trace without rethrowing

d)

Wrapping IOException into a DomainException with context

59.

Which scenario most clearly involves exception reflecting?

a)

Catching and rethrowing the same exception

b)

Wrapping a NullPointerException into IllegalStateException

c)

Logging only and continuing

d)

Suppressing the error with default values

60.

During which phase would a missing checked exception declaration be detected?

a)

Compile-time checking

b)

Runtime execution

c)

JVM bytecode loading

d)

Unit testing

61.

Which pairing correctly matches keyword to role in Java exceptions?

a)

throw: create object, throws: declare

b)

throw: log error, throws: terminate

c)

throw: catch error, throws: convert

d)

throw: declare, throws: create

62.

Which statement best distinguishes compile-time errors from runtime errors?

a)

Compile-time only logic mistakes, runtime only syntax issues

b)

Compile-time before execution, runtime during execution

c)

Compile-time during execution, runtime before execution

d)

Both occur only after deployment, not during tests

63.

To create a custom checked exception in Java, which class should you extend?

a)

RuntimeException class

b)

Exception class directly

c)

Error superclass

d)

Throwable interface

64.

To create a custom unchecked exception in Java, which base type is appropriate?

a)

Extend RuntimeException

b)

Extend Exception

c)

Implement AutoCloseable

d)

Extend IOException

65.

In a method signature, what does the throws keyword indicate?

a)

Method may propagate a checked exception

b)

Method will catch the exception internally

c)

Method masks exceptions with a wrapper

d)

Method creates a new exception object

66.

Inside a method body, what is the purpose of the throw statement?

a)

Convert checked exceptions to unchecked

b)

Log and ignore the exception silently

c)

Declare potential exceptions to callers

d)

Immediately trigger a specific exception

67.

Given public int divideBy(int x) throws NonPositiveException, when should NonPositiveException be thrown?

a)

When x is less than or equal to zero

b)

When integer division has no remainder

c)

When x equals one hundred exactly

d)

When x is greater than zero only

68.

Which snippet correctly demonstrates throw vs throws for a file read method?

a)

Method declares nothing, body logs without throwing

b)

Method declares throws RuntimeException, body catches IOException

c)

Method declares throws IOException, body throws new IOException

d)

Method declares throws Exception, body returns silently

69.

Which exception is typically unchecked in Java arithmetic operations?

a)

SQLException

b)

IOException

c)

ArithmeticException

d)

FileNotFoundException

70.

A method that reads a file must handle which requirement regarding exceptions?

a)

Declare throws IOException or catch it

b)

Declare throws ArithmeticException always

c)

Never use try–catch inside it

d)

Always convert to RuntimeException

71.

When masking an exception, what is the usual outcome?

a)

Suppress and ignore the original fully

b)

Log only without throwing anything

c)

Convert checked to unrelated runtime silently

d)

Wrap original inside a custom domain exception

72.

In the masking example, which original exception is wrapped by DataAccessException?

a)

SQLException from connectDatabase

b)

ArithmeticException from division

c)

NullPointerException from parsing

d)

IOException from readConfigFile

73.

Reflecting an exception means what in practice?

a)

Log and convert to return code

b)

Catch and rethrow the same exception

c)

Replace with a different exception

d)

Swallow and continue execution

74.

In loadConfig(), reflecting occurs in the catch block by doing which action?

a)

throw e to propagate unmodified

b)

return silently without throw

c)

throw new RuntimeException(e)

d)

e.printStackTrace only

75.

Which is a correct logging technique in a catch block for ArithmeticException?

a)

Always mask with DataAccessException

b)

Use throws to declare logging

c)

Reassign e to a new variable name

d)

Call e.printStackTrace to record details

76.

Which choice best describes a checked exception?

a)

Thrown exclusively by JVM internals

b)

Never needs to be handled by callers

c)

Occurs only due to programmer mistakes

d)

Must be declared or caught at compile time

77.

Which choice best describes an unchecked exception?

a)

Always originates from I/O operations only

b)

Subclass of Exception requiring throws in signatures

c)

Subclass of RuntimeException not required to declare

d)

Must be wrapped before propagation always

78.

When calling two methods, one throwing IOException and one dividing numbers, which should you handle explicitly?

a)

Handle the unchecked ArithmeticException only

b)

Handle the checked IOException explicitly

c)

Handle both with identical declarations

d)

Handle neither to avoid overhead

79.

What is a sound reason to mask a low-level SQLException with DataAccessException?

a)

Convert it into compile-time syntax warnings

b)

Force callers to ignore database failures

c)

Provide domain-specific context while preserving cause

d)

Hide all details to avoid any debugging

80.

In Java, what is the primary role of a finally block in a try-catch-finally construct?

a)

It handles unchecked exceptions only

b)

It executes after try and catch always

c)

It rethrows the current exception automatically

d)

It prevents exceptions from propagating

81.

Which order of catch blocks prevents unreachable code when handling exceptions FileNotFoundException, NumberFormatException, and Exception?

a)

NumberFormatException, FileNotFoundException, Exception

b)

Exception, NumberFormatException, FileNotFoundException

c)

NumberFormatException, Exception, FileNotFoundException

d)

FileNotFoundException, NumberFormatException, Exception

82.

A method C throws a checked exception that is caught in method A after calls A → B → C. Which statement best describes this flow?

a)

Exception cannot cross method boundaries

b)

Exception is swallowed in B automatically

c)

Exception propagates from C to A through B

d)

Exception must be converted to RuntimeException

83.

You must create InvalidAgeException extending RuntimeException and throw it when age < 0 or age > 150. Why extend RuntimeException here?

a)

To force callers to declare throws clause

b)

To enable multiple catch blocks to work

c)

To avoid compile-time checking for this rule

d)

To guarantee logging occurs automatically

84.

In a multi-catch scenario reading a file, parsing an integer, then dividing, which exception most likely indicates the file path does not exist?

a)

ArithmeticException from division by zero

b)

NumberFormatException from parse failure

c)

FileNotFoundException from missing file

d)

IOException from network timeout

85.

When would a NumberFormatException be the correct catch target in the sequence read → parse → divide?

a)

When the file handle closes early

b)

When the file is missing entirely

c)

When the parsed text is non-numeric

d)

When the division result is infinity

86.

Given try { read file; parse number; divide result; } with separate catches for FileNotFoundException, NumberFormatException, and Exception, what is the purpose of the final catch(Exception e)?

a)

Convert checked exceptions to errors

b)

Handle any exceptions not matched earlier

c)

Handle only unchecked exceptions generically

d)

Prevent finally block from executing

87.

Which statement about finally blocks is accurate regarding control flow with return statements inside try or catch?

a)

Finally is skipped if try returns

b)

Finally executes even if try returns

c)

Finally runs only when an exception occurs

d)

Finally runs only if catch executes

88.

Design a method that validates age using InvalidAgeException. Which approach correctly signals invalid input?

a)

Return -1 to indicate invalid age

b)

Log a warning and continue silently

c)

Throw new InvalidAgeException("age out of range")

d)

Catch and ignore NumberFormatException

89.

In the chain A → B → C, C throws IOException and B does not catch it. What must be true in method signatures for compilation?

a)

Neither needs throws because IOException is unchecked

b)

Only B must declare throws IOException

c)

Only A must declare throws IOException

d)

A and B must declare throws IOException

90.

What is the safest placement of a general catch(Exception e) relative to specific exceptions in a list of catch blocks?

a)

First, before all specific catches

b)

Anywhere, order does not matter

c)

Last, after all specific catches

d)

Between two specific catches only

91.

A student writes code with try-catch-finally where finally closes a file stream. Why is this practice recommended?

a)

Finally guarantees resource cleanup

b)

Finally prevents all runtime errors

c)

Finally avoids checked exceptions entirely

d)

Finally improves parsing accuracy

92.

What is the purpose of the Iterable interface?

a)

It prints elements automatically

b)

It provides a way to produce an Iterator

c)

It allows modifications to internal structure

d)

It sorts the collection

93.

Which method enables foreach iteration?

a)

iterator()

b)

hasNext()

c)

next()

d)

forEach()

94.

What does the Iterator interface NOT guarantee?

a)

Ability to check if more elements exist

b)

Ability to restart iteration

c)

Order of traversal

d)

Ability to remove elements

95.

What requirement must a class meet to use foreach loops?

a)

It must extend List

b)

It must implement Iterator

c)

It must implement Iterable

d)

It must implement Collection

96.

What happens when next() is called but hasNext() is false?

a)

It resets the iterator

b)

It returns null

c)

Nothing happens

d)

It throws NoSuchElementException

97.

Which statement about remove() is TRUE?

a)

It must always be supported

b)

It is optional and may throw UnsupportedOperationException

c)

It clears the collection

d)

It removes all elements

98.

Which of the following standard collections guarantee iteration order?

a)

TreeSet

b)

LinkedHashSet

c)

HashSet

d)

HashMap

99.

Which iterator implementation supports fail-fast behavior?

a)

Iterators using arrays

b)

None of them

c)

All custom iterators

d)

java.util collection iterators (ArrayList, HashMap)

100.

What pattern is applied when hiding internal structure behind an iterator?

a)

Factory Pattern

b)

Representation Exposure Prevention (REP)

c)

Builder Pattern

d)

Singleton Pattern

101.

Why are iterators commonly implemented as inner classes?

a)

They must be public

b)

They need direct access to private fields

c)

They replace constructors

d)

They require static keyword

102.

Which is TRUE about generic iterators?

a)

They force runtime casting of elements

b)

They cannot use type parameters

c)

They enable compile-time type safety

d)

They require raw types for collections

103.

In a fail-fast iterator, what typically triggers ConcurrentModificationException?

a)

Calling next() repeatedly

b)

Updating the collection structurally during iteration

c)

Invoking hasNext() on an empty iterator

d)

Creating two iterators on one collection

104.

Which method combination forms the minimal Iterator contract?

a)

hasNext(), next(), remove()

b)

size(), get(), set()

c)

stream(), collect(), map()

d)

iterator(), forEach(), remove()

105.

Which statement best describes foreach over an Iterable?

a)

It guarantees constant-time traversal

b)

It restarts iteration after completion

c)

It copies elements before iteration

d)

It uses the object's iterator() method implicitly

106.

What is a safe way to remove elements during iteration over a List?

a)

Create a new list and swap references

b)

Use the iterator's remove() after calling next()

c)

Modify the list directly via list.remove(index)

d)

Call clear() before iterating

107.

Which operation happens in a mapping iterator?

a)

Filtering data

b)

Removing duplicates

c)

Transforming input to output

d)

Sorting elements

108.

What is the output type of an Iterable?

a)

Any type

b)

Object

c)

Iterator

d)

T

109.

A reverse iterator changes what behavior?

a)

Iterates from end to start

b)

Changes hasNext behavior

c)

Only changes next behavior

d)

Merges two collections

110.

Which iterator is used in Java streams under the hood?

a)

Iterable

b)

Iterator

c)

Spliterator

d)

Scanner

111.

Mapping iterators support which data scope?

a)

Only for List collections

b)

Multiple data types

c)

Only String type

d)

Not for custom classes

112.

Which statement best describes fail-fast behavior in Java iterators?

a)

Iterator restarts from the beginning after any modification

b)

Iterator locks the collection to prevent any concurrent changes

c)

Iterator silently skips modified elements during traversal

d)

Iterator throws ConcurrentModificationException on structural change

113.

When should a custom collection implement Iterable?

a)

To guarantee thread-safe iteration in all cases

b)

To support bidirectional iteration by default

c)

To allow random indexing for quicker access

d)

To enable foreach iteration without exposing internals

114.

What is the core difference between Iterable and Iterator?

a)

Iterable supports remove(); Iterator exposes iterator()

b)

Iterable defines iterator(); Iterator performs traversal

c)

Iterable provides hasNext(); Iterator provides next()

d)

Iterable allows structural changes; Iterator disallows them

115.

Why must next() throw NoSuchElementException when no elements remain?

a)

To indicate concurrent modification occurred

b)

To warn that remove() cannot be used anymore

c)

To signal invalid access beyond iteration end

d)

To notify the iterator was reset to the start

116.

Why does Java not support resetting an iterator to the beginning?

a)

Iterators are always immutable objects by contract

b)

Reset requires random access which lists cannot provide

c)

Resetting violates the fail-fast behavior guarantee

d)

Iterator is designed for forward-only simple traversal

117.

What is a benefit of implementing an inner iterator class inside a collection?

a)

Share iterators safely across multiple threads

b)

Access private outer fields without exposing them

c)

Avoid the need for hasNext() and next() methods

d)

Enable bidirectional iteration automatically

118.

What typically happens if you structurally modify a List during a foreach loop?

a)

The modification is silently ignored

b)

The iterator resets to the first element

c)

The loop continues but skips new elements

d)

A ConcurrentModificationException is thrown

119.

Why should internal storage (e.g., internalList) in custom collections be private?

a)

To enable automatic synchronization on the list

b)

To improve garbage collection performance significantly

c)

To ensure faster iteration over elements always

d)

To prevent representation exposure and protect invariants

120.

What is the difference between iterator.remove() and external structural modifications?

a)

External changes are ignored by fail-fast iterators

b)

remove() always throws NoSuchElementException

c)

Both operations are treated as safe during iteration

d)

remove() is safe within iterator; external changes trigger fail-fast

121.

Why might one use an iterator instead of index-based access?

a)

Some collections like sets do not support indexing

b)

Iterators guarantee O(1) access for all elements

c)

Iterators automatically sort elements during traversal

d)

Indexing always causes fail-fast exceptions

122.

True or False: All Java collections implement Iterable.

a)

True

b)

False

c)

Only Sets

d)

Only Lists

123.

True or False: Iterator.remove() is always available.

a)

True — available for Lists only

b)

True — required by the interface

c)

False — remove() is optional

d)

False — method is deprecated

124.

True or False: You can use multiple iterators on the same collection simultaneously.

a)

False — only one iterator is allowed

b)

True — safe even during structural changes

c)

True — but modifications may cause fail-fast

d)

False — foreach prevents additional iterators

125.

True or False: foreach uses Iterator internally.

a)

True

b)

Only for Lists

c)

Only for arrays

d)

False

126.

True or False: Iterable requires implementing next() method.

a)

True — Iterable must define next()

b)

False — Iterator implements next()

c)

True — next() in foreach is mandatory

d)

False — next() is provided by List

127.

True or False: Custom iterators can return values of a different type from internal storage.

a)

False — violates type erasure

b)

True — only with arrays

c)

False — must match storage type

d)

True — via mapping iterator

128.

Which situation most likely triggers ConcurrentModificationException during iteration?

a)

Reading elements with next() repeatedly

b)

Adding to the underlying collection externally

c)

Calling iterator.remove() when hasNext() is true

d)

Creating a second iterator without using it

129.

Which design goal is supported by keeping internal representation private in custom collections?

a)

Ensuring constant-time iteration

b)

Maintaining class invariants and REP

c)

Providing thread-safe iteration by default

d)

Enabling automatic bidirectional traversal

130.

An iterator is consumed after full traversal. Choose the correct statement.

a)

True for standard single-pass iterators

b)

False unless collection is immutable

c)

True only for primitive arrays

d)

False for all Java iterators

131.

Iterators guarantee sorting. Select the correct claim.

a)

False, order depends on source

b)

False, unless using TreeSet

c)

True, they always sort ascending

d)

True, if elements are comparable

132.

What does the code print? List list = List.of(1,2,3); Iterator it = list.iterator(); it.next(); it.next(); System.out.println(it.hasNext());

a)

true because third element remains

b)

false because iterator resets

c)

false because hasNext checks size only

d)

true because iterators loop forever

133.

What happens? List list = new ArrayList<>(); list.add("A"); Iterator it = list.iterator(); list.add("B"); it.next();

a)

Silently restarts iteration

b)

Returns "A" then continues

c)

Returns "B" without error

d)

Throws ConcurrentModificationException

134.

Foreach desugaring: for (String s : list) { ... } becomes which core pattern?

a)

Use iterator with hasNext and next

b)

Index loop over list.size()

c)

Recursion over sublists

d)

Stream forEach terminal op

135.

Identify the bug: if (!hasNext) { throw new NoSuchElementException(); }

a)

Negation should be removed

b)

Bracket placement is incorrect

c)

Exception type should be IllegalStateException

d)

hasNext is a method, call hasNext()

136.

What happens? Iterator it = list.iterator(); it.remove();

a)

IllegalStateException because next not called

b)

ConcurrentModificationException immediately

c)

Removes first element by default

d)

NoSuchElementException on empty list

137.

Design IntRange implements Iterable. Which constructor parameters are necessary to generate integers start to end inclusive?

a)

end and step size

b)

only start value

c)

start and end boundaries

d)

start, end, and capacity

138.

ReverseList implements Iterable for ArrayList. What is its iteration order?

a)

From last element to first

b)

From first element to last

c)

Interleaving even then odd

d)

Random access by hash

139.

EvenIterator implements Iterator. What should it do when encountering odd numbers?

a)

Return them unchanged

b)

Skip them during traversal

c)

Convert them to zero

d)

Throw UnsupportedOperationException

140.

MergedIterator merges two iterators. What is the primary behavior?

a)

Sequentially traverse first then second

b)

Randomly mix from both

c)

Sort combined elements ascending

d)

Deduplicate equal elements only

141.

MapperIterator requires which inputs to operate?

a)

Only a collection source

b)

Stream and collector

c)

Base iterator and mapping function

d)

Comparator and predicate

142.

A custom collection with inner iterator should minimally include which components?

a)

Tree root, leaves, balancing logic

b)

File store, cache layer, thread pool

c)

Internal list, custom iterator, foreach support

d)

Graph nodes, edges, traversal cost

143.

CharIterable("ABC") should produce which sequence when iterated?

a)

'A' then null then 'C'

b)

'C', 'B', 'A' reversed

c)

'A', 'B', 'C' in order

d)

"ABC" as one token

144.

Safe removal iterator design: which rule ensures legality of remove()?

a)

Call next() before remove()

b)

Never call next() during removal

c)

Call remove() twice consecutively

d)

Call hasNext() after remove()

145.

Which statement best describes hasNext() in typical iterators?

a)

Consumes the next element

b)

Sorts remaining elements

c)

Checks if a next element exists

d)

Resets iterator position

146.

When modifying a list during iteration with its iterator, why might ConcurrentModificationException occur?

a)

Calling next on empty list

b)

Using immutable collections

c)

Structural change outside iterator

d)

Reading through hasNext only

147.

Which iterator variant transforms elements while iterating, producing a different type?

a)

MapperIterator

b)

ReverseList iterator

c)

EvenIterator for filtering

d)

MergedIterator

148.

What is the primary purpose of assertions in Java?

a)

Replace all error handling

b)

Handle runtime exceptions

c)

Validate user input

d)

Check internal assumptions during development

149.

Which keyword is used to write an assertion?

a)

verify

b)

ensure

c)

check

d)

assert

150.

What happens if an assertion fails?

a)

Program continues normally

b)

The JVM turns off assertions

c)

AssertionError is thrown

d)

The compiler stops