Search code examples
javastringbooleanreplaceall

Cannot to replace a string to another (boolean value) - Java


boolean b1 = false;
boolean b2 = true;


String s = new String(b1+""+b2);

s.replaceAll("false", "f");
s.replaceAll("true", "t");

Nothing is replaced. I still get "false true". I want to replace all "false" and "true", of the String, to "f" and "t".

Im pretty sure Im not doing it the right way, and thats why I need your help, which will be greatly appreciated.


Solution

  • String in java is immutable, which means, once created, the value of a String object will not change.

    The method replaceAll() (or almost all other methods in String class) hence are designed to return a new string rather than modifying the old one.

    So the call should be made as

    s = s.replaceAll("false", "f");
    

    More on immutability is here