Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Technique used in java to make string immutable?

Technique used in java to make string immutable?
or how can i make my string class immutable.
I just want to know the logic behind this.

like image 827
gifpif Avatar asked Jul 24 '26 11:07

gifpif


1 Answers

In Java, String objects are already immutable.

I can't speak to how the Java language creators specifically made String immutable, but here are some guidelines that you can follow to make your own classes immutable:

  1. Don't use setter methods.
  2. Make all fields private and final.
  3. Don't allow methods to be overwritten (either make class final or use a factory pattern).
  4. If any fields are objects of mutable type, take care when using those objects: Defensively clone them when returning those objects off of a getter method or receiving them in the constructor, and don't provide methods which modify the mutable objects.
like image 127
Platinum Azure Avatar answered Jul 28 '26 15:07

Platinum Azure