user983246
user983246

Reputation: 1449

Are there immutable objects besides Strings in Java?

I only heard that strings in Java cannot be immutable and I was wondering are there other objects besides strings that are also immutable?

On a side note, are strings in C++ immutable too?

Upvotes: 0

Views: 357

Answers (2)

Patashu
Patashu

Reputation: 21793

All of the boxed primitives, for example Integer, are immutable.

You can make immutable classes yourself - for example, a class that sets its variables using its constructor, and has no public variables or setters.

Upvotes: 1

user1898811
user1898811

Reputation:

Many of the primitive types are immutable (Integer, Long, Boolean, etc). Immutability is not something that is explicitly noted in java, it's really a semantic contract. You can make any class immutable by declaring it's members as final, assigning them on construction, and locking down access through a class's public interface.

A String in C++ is a character array ending in a zero character. That's it. This has no promises of immutability, though use of const can help lock down access.

I guess the point is that many things in Java are immutable, but only the documentation and source can really prove this to you.

Upvotes: 3

Related Questions