Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As far as I know, Strings in Java are immutable and every time we try to change a String Java creates the new String in a String pool and re-references us to this new String. It is said that if we want to change a String we should use a String Builder or a String Buffer. My question is: What really happens when we use inbuilt String methods like trim(),replaceFirst(), and others that change created String. Does Java create a new String and still re-references or we change the already created String.

I tried to Google but didn't find an appropriate answer. It may be me whose google skills are not the best :) I hope that I've made my question clear and thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

String's are immutable - This is a fact in java (may be with exception from Reflection)

  1. A String object once created will not be modified
  2. Any operation performed using the reference variable pointing to the object either creates a new string object or points to an already existing different immutable string object

Do not do this

    public static void main(String[] args) throws Exception {
        String immutable = "immutable";
        String mutable = immutable;
        String anotherObject = ("immutable" + " ").trim();
        String internedCopy = anotherObject.intern();
        System.out.println(immutable + " - Initial object reference");
        System.out.println(mutable + " - Another reference to same object");
        System.out.println(anotherObject + " - Different object with same value");
        System.out.println(internedCopy + " - Reference to differently created object's internalized object");

        System.out.println("Now lets try something");
        Field field = String.class.getDeclaredField("value");
        field.setAccessible(true);
        char[] state = (char[]) field.get(mutable);
        state[0] = 'M';
        System.out.println(immutable + " - Initial object reference");
        System.out.println(mutable + " - Another reference to same object"); // this is the only acceptable change
        System.out.println(anotherObject + " - Different object with same value");
        System.out.println(internedCopy + " - Reference to differently created object's internalized object");
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...