Java OCA OCP Practice Question 774

Question

How many of the following variables represent immutable objects?

ArrayList l = new ArrayList(); 
String s = new String(); 
StringBuilder sb = new StringBuilder(); 
LocalDateTime t = LocalDateTime.now(); 
  • A. None
  • B. One
  • C. Two
  • D. Three
  • E. Four
  • F. None of the above?this code doesn't compile.


C.

Note

Mutable means the object can change state.

Immutable means the object cannot change state.

An ArrayList stores a collection of objects.

It mutates as the elements change.

A StringBuilder is also mutable as it improves performance by not creating a new object each time it changes.

A String is immutable. Methods that look like they change the value simply return a different String object.

The date/time objects added in Java 8, such as LocalDateTime, are also immutable.




PreviousNext

Related