Unable to replace string with another (boolean) - 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 the "false truth." I want to replace all the β€œfalse” and β€œtrue” String strings with β€œf” and β€œt”.

I am sure that I am not doing it right, and that is why I need your help, and we will be very grateful.

+1
source share
6 answers

A string in java is immutable, which means that after creation, the value of the String object will not change.

The replaceAll () method (or almost all other methods in the String class) is therefore intended to return a new line, and not to change the old one.

So the call should be done as

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

Read more about immutability here.

+5
source

Lines are immutable. When you perform any operations on strings, it creates a new line. You need to assign the results to the link again

It should be something like s = s.replaceAll("false", "f");

+7
source

When you call .replaceAll ("false", "f"), you don't mutate String at all. You need to assign this value to s like this:

 s = s.replaceAll("false", "f"); 
+4
source
 System.out.println(s.replaceAll("false", "f ").replaceAll("true", "t ")); 
+2
source

You need to write it like this:

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

Strings are immutable, so once you declare them, they cannot be changed. Call s.replaceAll("false", "f"); creates a new string object with "f" instead of "false" . Since you did not assign this new object to a variable, the new line was basically lost, and your left with the original line.

+2
source

First of all, you need to understand that String is immutable. This means that its contents cannot be modified. To get the result of the replaceAll () method, you need to assign the return value to String .

0
source

All Articles