Search code examples
javastringreplaceimmutabilityfinal

Using String.replace for copys of final Strings


I have the following Test:

public void testStringReplace()
    {    
        final String placeholder = "$ph$";
        final String template = "<test>" + placeholder + "</test>";
        final String result = "<test>Hello!</test>";

        String copyOfTemplate = template;
        copyOfTemplate.replace(placeholder, "Hello!");

        if(!copyOfTemplate.equals(result));
            fail();
    }

The test always fails, but why? How do I have to define copyOfTemplate, to be able to change it? Or am I missing some other detail here?


Solution

  • String is immutable so calling

    copyOfTemplate.replace(placeholder, "Hello!");
    

    without assigning it to anything effectively does nothing. It returns a new string with the replacement, which you're ignoring. Any half-decent IDE will warn you about this:

    IDE warning

    Also, String copyOfTemplate = template doesn't really do anything either. It's not a copy. It's just a new variable pointing to the same underlying string. There is no method to copy a string because, again, strings are immutable so a copy becomes useless.

    You want

    String copyOfTemplate = template.replace(placeholder, "Hello!");
    

    I suggest reading the Oracle tutorial on strings. It seems like you've missed some of the fundamentals.