Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

java - Does inbuilt String methods usage create new strings

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

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

1 Reply

0 votes
by (71.8m points)

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");
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...