In an interview they asked me to write a program to prove String is immutable. I don't have any idea what to write, somebody please help me ?'
-
2Have you googled it? http://stackoverflow.com/questions/8798403/string-is-immutable-what-exactly-is-the-meaning – Beri Jan 12 '15 at 12:54
-
1`String str = ""; str.replace("y", "n"); System.out.println(str);`, and don't work there. – Maroun Jan 12 '15 at 12:54
-
2possible duplicate of [Is a Java string really immutable?](http://stackoverflow.com/questions/20945049/is-a-java-string-really-immutable) – grattmandu03 Jan 12 '15 at 12:55
-
Isn't the only way to prove it to quote the language spec? There might be all manner of tricks/bugs which can be exploited on this or that JVM to show that a string is or isn't immutable, but if the standard says it's immutable then it's immutable. – Jan 12 '15 at 13:04
-
1I'm thinking it is actually impossible to "PROVE" that `String` is immutable, because immutable objects is more of a paradigm than a construct. So, I could have an immutable class that has a thousand methods and one of them accidentally mutates the object. So, to prove `String` is immutable would require an exhaustive use of all its functions to show that they do not mutate the `String` - a futile exercise, indeed. – ryvantage Jan 12 '15 at 13:12
7 Answers
use the class sun.misc.Unsafe and change the content of the String, to prove the opposite. You should know when something is impossible.
import sun.misc.Unsafe; import java.lang.reflect.Field;
class Main {
static Unsafe getUnsafe() throws Throwable {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe) f.get(null);
}
public static void main(String[] args) throws Throwable {
String a = "abcdef";
Unsafe u = getUnsafe();
int stringOffset = 40; //this might be platform dependant I used guessing in a loop and keept what whorked.
System.out.println(a); // abcdef
u.putChar(a,stringOffset + 0 * u.ARRAY_CHAR_INDEX_SCALE, 'g');
u.putChar(a,stringOffset + 1 * u.ARRAY_CHAR_INDEX_SCALE, 'h');
u.putChar(a,stringOffset + 2 * u.ARRAY_CHAR_INDEX_SCALE, 'i');
System.out.println(a); // ghidef
}
}
you might get warnings because of the usage of Unsafe

- 7,921
- 9
- 48
- 66
To show String is immutable you have to show that once you create one, you won't be able to change it. So you have to show that all public methods of the class don't change it. But you also have to show that you can't inherit from it because that could be a way to break this characteristic (or else that it state couldn't be changed by overriders).

- 139
- 6
String objects created using string literals are stored in the String Constant Pool and any two objects in the pool can’t have the same content.
public class MyClass {
public static void main(String[] args) {
String s1 = "java";
String s2 = "java";
System.out.println("No modification is made");
referenceCheck(s1,s2);
s1 = s1.concat("code");
System.out.println("After modification");
referenceCheck(s1,s2);
}
public static void referenceCheck(Object x, Object y)
{
if(x==y)
{
System.out.println("Both objects points to same reference");
}
else
{
System.out.println("Both pointing to different object");
}
}
Before modifications, they are pointing to the same object. Once we tried to change the content of the object using ‘s1’, a new object is created in the pool and its reference is assigned to s1. If the strings are mutable, both s1 and s2 should point to the same object even after modification.

- 607
- 6
- 18
To prove for immutability, use the following code:
public class Mutable {
public static void main(String[] s) {
String a = "abc";
String b = a;
a = a.concat("d");
System.out.println(a);
System.out.println(b);
StringBuffer c = new StringBuffer("abc");
StringBuffer d = c;
c.append("d");
System.out.println(c);
System.out.println(d);
}
}
The class which is mutable will show same results since the references of the variables are the same.

- 166
- 1
- 10
String first = "CATCAT";
String second = first.replace('A', 'Z');
System.out.println("First = " + first);
System.out.println("Second = " + second);
The initial String is still the same.

- 1,893
- 1
- 18
- 38
-
4this does only show that replace creates a new string instead of working on the current string. You can't prove by giving an example. – Arne Jan 12 '15 at 12:59
-
1This doesn't prove `String` is immutable, only that the `replace()` function does not mutate the `String`. – ryvantage Jan 12 '15 at 13:09
-
1How does that prove it? You only showed that a specific method doesn't change the class. It's hardly a proof. – Avi Jan 12 '15 at 13:12
May be you can do like this
String str1="String1";
String str2 = "String2";
System.out.println("str1 " + str1.hashCode());
System.out.println("str2 = " + str2.hashCode());
str1=str1 + str2;
System.out.println("The hashcode str1 changed : " + str1.hashCode());
Hence proved

- 1,598
- 1
- 12
- 18
-
You get different hash code from different object. Don't see how it prove anything. – talex Jan 12 '15 at 13:17
-
so you itself telling that str1 is different object after concatinating. so if the value is changed it will be created as new object so new hash code. hence i proved. will you accept? – Kalaiarasan Manimaran Jan 12 '15 at 13:19
-
Value of `str1` variable changes indeed. But not string itself. If you store it in some temp variable you see that string is same. – talex Jan 12 '15 at 13:22
-
how you say that string is not changed? string str1 changed and for proving that its hash code also changed. – Kalaiarasan Manimaran Jan 12 '15 at 13:24
-
`str1` is not string. It is variable. Yes it now point to different object. But we talking about string object. and it doesn't changes. – talex Jan 12 '15 at 13:26
-
Here is the following example:
public class Immutable {
public static void main(String[] args) {
String str1 = "123";
String str2 = "123";
System.out.println(str1 == str2); //Output : true
str1 = str2 + "456";
System.out.println(str1 == str2); //Output : false
}
}

- 4,861
- 11
- 59
- 73

- 440
- 1
- 8
- 19