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.
Asked
Active
Viewed 792 times
2

gifpif
- 4,507
- 4
- 31
- 45
-
2String is already immutable. – kiheru Aug 17 '13 at 15:10
-
3JDK provides source code for Java standard classes in `src.zip` file. Take a look at String class code and you will see how it is done. Also take a look at [how-to-create-immutable-objects-in-java](http://stackoverflow.com/questions/6305752/how-to-create-immutable-objects-in-java) – Pshemo Aug 17 '13 at 15:11
-
@Pshemo In `src.zip` contain all publicly available source files. but its hard to understand for beginners. :( – gifpif Aug 17 '13 at 15:26
-
@PawanMishra Nobody said it will be easy :/ That is why I gave you second link so you could see what to looking for. To make viewing easier you can use this file in IDE like Eclipse or NetBeans and press `method()` with Ctrl key to navigate to method declaration/implementation. – Pshemo Aug 17 '13 at 15:31
-
Note: String is effectively immutable, but technically it has two mutable fields in Java 7. These are used to cache the hashCode(s). – Peter Lawrey Aug 18 '13 at 06:34
2 Answers
7
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:
- Don't use setter methods.
- Make all fields
private
andfinal
. - Don't allow methods to be overwritten (either make class
final
or use a factory pattern). - 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.

Platinum Azure
- 45,269
- 12
- 110
- 134
-
+1 for `either make class final or use a factory pattern` - most of the time have heard of only `final` one but this `factory pattern` seems promising too :) – exexzian Aug 17 '13 at 15:16
2
String
class in Java is already immutable.
For reference, see the documentation at http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
If you want to see how Java String class is implemented, please visit http://docjar.com/html/api/java/lang/String.java.html

Garbage
- 1,490
- 11
- 23