2

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 ?'

User666
  • 855
  • 1
  • 7
  • 7
  • 2
    Have 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
  • 2
    possible 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
  • 1
    I'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 Answers7

4

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

Arne
  • 7,921
  • 9
  • 48
  • 66
1

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).

1

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.

aspan88
  • 607
  • 6
  • 18
0

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.

Xavier Mukodi
  • 166
  • 1
  • 10
-1
    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.

robin
  • 1,893
  • 1
  • 18
  • 38
  • 4
    this 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
  • 1
    This doesn't prove `String` is immutable, only that the `replace()` function does not mutate the `String`. – ryvantage Jan 12 '15 at 13:09
  • 1
    How 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
-1

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

Kalaiarasan Manimaran
  • 1,598
  • 1
  • 12
  • 18
-1

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
    }
}
Ivan Aracki
  • 4,861
  • 11
  • 59
  • 73
levan
  • 440
  • 1
  • 8
  • 19