Because Boolean
is immutable. See: Why Wrapper class like Boolean in java is immutable? and my answer:
Because 2
is 2. It won't be 3
tomorrow.
Immutable is always preferred as the default, especially in multithreaded situations, and it makes for easier to read and more maintainable code. Case in point: the Java Date
API, which is riddled with design flaws. If Date
were immutable the API would be very streamlined. I would know Date
operations would create new dates and would never have to look for APIs that modify them.
Read Concurrency in Practice to understand the true importance of immutable types.
But also note that if for some reason you want mutable types, use AtomicInteger
AtomicBoolean
, etc. Why Atomic
? Because by introducing mutability you introduced a need for threadsafety. Which you wouldn't have needed if your types stayed immutable, so in using mutable types you also must pay the price of thinking about threadsafety and using types from the concurrent
package. Welcome to the wonderful world of concurrent programming.
Also, for Boolean
- I challenge you to name a single operation that you might want to perform that cares whether Boolean is mutable. set to true? Use myBool = true
. That is a re-assignment, not a mutation. Negate? myBool = !myBool
. Same rule. Note that immutability is a feature, not a constraint, so if you can offer it, you should - and in these cases, of course you can.
Note this applies to other types as well. The most subtle thing with integers is count++
, but that is just count = count + 1
, unless you care about getting the value atomically... in which case use the mutable AtomicInteger
.