Are all primitive wrapper classes in Java immutable objects? String is immutable. What are the other immutable objects?
Are all primitive wrapper classes in Java immutable objects? String is immutable. What are
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Any type which doesn’t give you any means to change the data within it is immutable – it’s as simple as that. Yes, all the primitive wrapper types are immutable1, as is
String. UUID, URL andURIare other examples.Although
CalendarandDatein the built-in Java API are mutable, many of the types within Joda Time are immutable – and to my mind, this is one reason why Joda Time is easier to work with. If an object is immutable, you can keep a reference to it somewhere else in your code and not have to worry about whether or not some other piece of code is going to make changes – it’s easier to reason about your code.1 by which I mean
java.lang.Integeretc. As noted elsewhere, theAtomic*classes are mutable, and indeed have to be in order to serve their purpose. There’s a difference in my mind between “the standard set of primitive wrapper classes” and “the set of classes which wrap primitive values”.You can write your own mutable wrapper class very easily:
So as you can see, there’s nothing inherently immutable about wrapper classes – it’s just that the standard ones were designed to be immutable, by virtue of not providing any way to change the wrapped value.
Note that this allows for the same object to be used repeatedly when boxing, for common values: