1

String str1 = "The rumour is that the neighbours displayed good behaviour by labouring to help Mike because he is favoured.";

str1.replaceAll("our", "or");

System.out.println(str1);

  • 5
    `String`s are immutable - `str1.replaceAll("our", "or");` does not change `str1`. The result (a new `String`) needs to be assigned and used. For example: `str1 = str1.replaceAll("our", "or");`. – Andrew S Feb 04 '22 at 22:13
  • 1
    Does this answer your question? [Immutability of Strings in Java](https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java) – Karl Knechtel Feb 04 '22 at 22:22
  • @KarlKnechtel I think it doesn't answer this question. Because answer to question "why string doesn't changed" is "string immutability". And "[Immutability of Strings in Java](https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java)" is the answer to question "what is string immutability". – Anton Serdyuchenko Feb 04 '22 at 22:39

1 Answers1

1

Method replaceAll returns a new string where each occurrence of the matching substring is replaced with the replacement string.

Your code doesn't work because String is immutable. So, str1.replaceAll("our", "or"); doesn't change str1.

Try this code:

    String str1 = "I am trying to replace the pattern.";
    String str2 = str1.replaceAll("replace", "change");
    System.out.println(str2);

If you don't what str2, try this code:

    String str1 = "I am trying to replace the pattern.";
    System.out.println(str1.replaceAll("replace", "change"));

And read about Immutability of Strings in Java.