Immutable Classes

1.Which of the following is a characteristic of an immutable class?
  • A. Its state can be changed after creation.
  • B. All its fields are public.
  • C. Its state cannot be modified after it is created.
  • D. It must implement the Cloneable interface.

Its state cannot be modified after it is created.

Its state cannot be modified after it is created.

2.To make a class immutable, what should be the access modifier for all its fields?
  • A. public
  • B. protected
  • C. private and final
  • D. default

private and final

private and final

3.If an immutable class contains mutable objects (e.g., Date or ArrayList), what should be done in the constructor and getter methods to ensure immutability?
  • A. Simply assign the mutable object directly.
  • B. Make defensive copies of the mutable objects.
  • C. Declare the mutable objects as volatile.
  • D. Do not allow mutable objects in immutable classes.

Make defensive copies of the mutable objects.

Make defensive copies of the mutable objects.

4.Which of the following built-in Java classes is an example of an immutable class?
  • A. java.util.Date
  • B. java.lang.String
  • C. java.util.ArrayList
  • D. java.lang.StringBuilder

java.lang.String

java.lang.String

5.What is a key advantage of using immutable classes?
  • A. They consume less memory.
  • B. They are inherently thread-safe and easier to reason about in concurrent environments.
  • C. They allow for dynamic modification of objects at runtime.
  • D. They provide better performance for all operations.

They are inherently thread-safe and easier to reason about in concurrent environments.

They are inherently thread-safe and easier to reason about in concurrent environments.