-1

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.

3
  • Look into the source code. Commented Feb 7, 2021 at 17:45
  • 1
    "every time we try to change a String Java creates the new String in a String pool" --- Incorrect! It creates a new String, but the string is unlikely to be in the string pool. Commented Feb 7, 2021 at 17:51
  • 2
    "Does Java create a new String" Yes. --- "or we change the already created String" Never! Commented Feb 7, 2021 at 17:52

2 Answers 2

2

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");
    }
Sign up to request clarification or add additional context in comments.

Comments

1

As already stated, Strings are immutable and can and will never be changed. You can only change the reference stored in your variable.

You can already tell that the string itself does not get modified as when you call those functions, they return a new string and do not change the one you invoked the function on, as you need to do newString = oldString.trim();

When looking at the source code of the two functions you mentioned, there is a creation of Strings in both of those. In the first one (trim()), it just creates a new String from a byte[]-Copy of the original string, in the bounds of non-whitespace characters. The second function (replaceFirst()) calls a few helper functions, but the returning String instance comes from a StringBuilder instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.