Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Java wrapper classes immutable?

Tags:

I know the usual reasons that apply to general immutable classes, viz

  1. can not change as a side effect
  2. easy to reason about their state
  3. inherently thread safe
  4. no need to provide clone/copy constructor/factory copy method
  5. instance caching
  6. no need for defensive copies.

However, wrapper classes represent primitive types, and primitive types are mutable. So why aren't wrapper classes mutable?

like image 312
shrini1000 Avatar asked Sep 11 '12 13:09

shrini1000


People also ask

Why are classes immutable in Java?

An immutable class is good for caching purposes because you don't have to worry about the value changes. Another benefit of immutable class is that it is inherently thread-safe, so you don't have to worry about thread safety in case of multi-threaded environment.

Is wrapper class immutable?

In Java Immutable class is a class which once created and it's contents can not be changed. On same concept Immutable objects are the objects whose state can not be changed once constructed.

Why is Java immutable important?

The advantage of immutable objects is that you know their data cannot change, so you don't have to worry about that. You can pass them around freely without having to remember whether a method you pass them to could change them in a way your code is not prepared to handle. That makes working with immutable data easier.

What are immutable classes in Java?

What Is an Immutable Class in Java? Immutable class means once the object of the class is created its fields cannot be modified or changed. In Java, all the wrapper classes like Boolean, Short, Integer, Long, Float, Double, Byte, Char, and String classes are immutable classes.


1 Answers

However, wrapper classes represent primitive types, and primitive types (except String) are mutable.

Firstly, String isn't a primitive type.

Secondly, it makes no sense to talk about the primitive types being mutable. If you change the value of a variable like this:

int x = 5; x = 6; 

That's not changing the number 5 - it's changing the value of x.

While the wrapper types could have been made mutable, it would have been annoying to do so, in my view. I frequently use readonly collections of these types, and wouldn't want them to be changeable. Very occasionally I want a mutable equivalent, but in that case it's easy enough to come up with one, or use the Atomic* classes.

I find myself wishing that Date and Calendar were immutable far more often than I find myself wanting Integer to be mutable... (Of course I normally reach for Joda Time instead, but one of the benefits of Joda Time is immutability.)

like image 94
Jon Skeet Avatar answered Nov 30 '22 07:11

Jon Skeet