Immutability of Strings in Java

后端 未结 26 2313
不思量自难忘°
不思量自难忘° 2020-11-21 06:33

Consider the following example.

String str = new String();

str  = \"Hello\";
System.out.println(str);  //Prints Hello

str = \"Help!\";
System.out.println(s         


        
相关标签:
26条回答
  • 2020-11-21 07:13

    For those wondering how to break String immutability in Java...

    Code

    import java.lang.reflect.Field;
    
    public class StringImmutability {
        public static void main(String[] args) {
            String str1 = "I am immutable";
            String str2 = str1;
    
            try {
                Class str1Class = str1.getClass();
                Field str1Field = str1Class.getDeclaredField("value");
    
                str1Field.setAccessible(true);
                char[] valueChars = (char[]) str1Field.get(str1);
    
                valueChars[5] = ' ';
                valueChars[6] = ' ';
    
                System.out.println(str1 == str2);
                System.out.println(str1);
                System.out.println(str2);           
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
    
        }
    }
    

    Output

    true
    I am   mutable
    I am   mutable
    
    0 讨论(0)
  • 2020-11-21 07:14

    If HELLO is your String then you can't change HELLO to HILLO. This property is called immutability property.

    You can have multiple pointer String variable to point HELLO String.

    But if HELLO is char Array then you can change HELLO to HILLO. Eg,

    char[] charArr = 'HELLO';
    char[1] = 'I'; //you can do this
    

    Programming languages have immutable data variables so that it can be used as keys in key, value pair.

    0 讨论(0)
  • 2020-11-21 07:17

    Immutability implies that the value of an instantiated object cannot change, you can never turn "Hello" into "Help!".

    The variable str is a reference to an object, when you assign a new value to str you aren't changing the value of the object it references, you are referencing a different object.

    0 讨论(0)
  • 2020-11-21 07:17

    Like Linus Tolvards said:

    Talk is cheap. Show me the code

    Take a look at this:

    public class Test{
        public static void main(String[] args){
    
            String a = "Mississippi";
            String b = "Mississippi";//String immutable property (same chars sequence), then same object
    
            String c = a.replace('i','I').replace('I','i');//This method creates a new String, then new object
            String d = b.replace('i','I').replace('I','i');//At this moment we have 3 String objects, a/b, c and d
    
            String e = a.replace('i','i');//If the arguments are the same, the object is not affected, then returns same object
    
            System.out.println( "a==b? " + (a==b) ); // Prints true, they are pointing to the same String object
    
            System.out.println( "a: " + a );
            System.out.println( "b: " + b );
    
            System.out.println( "c==d? " + (c==d) ); // Prints false, a new object was created on each one
    
            System.out.println( "c: " + c ); // Even the sequence of chars are the same, the object is different
            System.out.println( "d: " + d );
    
            System.out.println( "a==e? " + (a==e) ); // Same object, immutable property
        }
    }
    

    The output is

    a==b? true
    a: Mississippi
    b: Mississippi
    c==d? false
    c: Mississippi
    d: Mississippi
    a==e? true
    

    So, remember two things:

    • Strings are immutable until you apply a method that manipulates and creates a new one (c & d cases).
    • Replace method returns the same String object if both parameters are the same
    0 讨论(0)
  • 2020-11-21 07:19

    String is immutable means that you cannot change the object itself, but you can change the reference to the object. When you called a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty". Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:

    Foo x = new Foo("the field");
    x.setField("a new field");
    System.out.println(x.getField()); // prints "a new field"
    

    While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:

    String s = "some text";
    s.substring(0,4);
    System.out.println(s); // still printing "some text"
    String a = s.substring(0,4);
    System.out.println(a); // prints "some"
    
    0 讨论(0)
  • 2020-11-21 07:19
        public final class String_Test {
    
        String name;
        List<String> list=new ArrayList<String>();
    
        public static void main(String[] args) {
    
            String_Test obj=new String_Test();
            obj.list.add("item");//List will point to a memory unit- i.e will have one Hashcode value #1234
    
            List<String> list2=obj.list; //lis1 also will point to same #1234
    
            obj.list.add("new item");//Hashcode of list is not altered- List is mutable, so reference remains same, only value in that memory location changes
    
            String name2=obj.name="Myname"; // name2 and name will point to same instance of string -Hashcode #5678
            obj.name = "second name";// String is Immutable- New String HAI is created and name will point to this new instance- bcoz of this Hashcode changes here #0089
    
            System.out.println(obj.list.hashCode());
            System.out.println(list2.hashCode());
            System.out.println(list3.hashCode());
    
            System.out.println("===========");
            System.out.println(obj.name.hashCode());
            System.out.println(name2.hashCode());
        }
    }
    

    Will produce out put something like this

    1419358369 1419358369

    103056 65078777

    Purpose of Immutable object is that its value should not be altered once assigned. It will return new object everytime you try to alter it based on the implementation. Note: Stringbuffer instead of string can be used to avoid this.

    To your last question :: u will have one reference , and 2 strings in string pool.. Except the reference will point to m!ss!ss!pp!

    0 讨论(0)
提交回复
热议问题