NEW
Font size
WorksheetsThe oops moment/3
Total questions: 10
Worksheet time: 5mins
What is the primary reason to use defensive copying when returning a list from a class?
To save memory
To prevent external modification of the internal state
To confuse other developers
To automatically sort the list
If you return a list directly from a class and another part of your code modifies it, what OOP principle is being violated?
Encapsulation
Polymorphism
Abstraction
Inheritance
Which collection is better if you’re doing frequent insertions and deletions in the middle of the list?
ArrayList
LinkedList
HashMap
Vector
A class allows you to borrow books. You now want to borrow multiple books at once. What should you add?
A loop in the main method
A new method like borrowMultipleBooks()
Delete all books
Make the list static
What helps prevent an object from reaching an invalid state?
Logging everything
Skipping validations
Enforcing business rules
Using only primitive data types
Why use getters/setters instead of public variables?
They're shorter to write
They confuse the user
They allow control over how variables are accessed/modified
They are required by Java
What does it mean for an object to be immutable?
It can’t be accessed by other classes
It can’t be changed after it's created
It’s slower to execute
It throws exceptions when used
—Defensive copying—
public List<String> getAuthors() {
// ?
}
Which line correctly implements defensive copying?
return authors;
return authors.clone();
return new ArrayList<>(authors);
return null;
public class Library {
private List<String> books;
// ?
}
Which constructor properly initializes books?
public Library() { books.clear(); }
public Library() { books = new ArrayList<>(); }
Library() => books = [];
new Library() { books = null; }
public void setTitle(String title) {
// ?
}
Which code correctly throws an exception for invalid input?
this.title = title;
if (title.length() == 0) return;
if (title == null) throw new IllegalArgumentException("Invalid title");
System.out.println("Invalid title");
