48

I am a little bit confused at the moment. I tried that:

String test = "KP 175.105";
test.replace("KP", "");
System.out.println(test);

and got:

KP 175.105

However, I want:

175.105

What's wrong with my code?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
maximus
  • 11,264
  • 30
  • 93
  • 124

3 Answers3

163

You did not assign it to test. Strings are immutable.

test = test.replace("KP", "");

You need to assign it back to test.

shmosel
  • 49,289
  • 6
  • 73
  • 138
PSR
  • 39,804
  • 41
  • 111
  • 151
21

Strings are immutable so you need to assign your test reference to the result of String.replace:

test = test.replace("KP", "");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
7

String is immutable in java so you have to do

test =test.replace("KP", "");
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39