46

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
  • 63,838
  • 26
  • 184
  • 242
maximus
  • 10,894
  • 28
  • 91
  • 124

3 Answers3

146

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

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

You need to assign it back to test.

shmosel
  • 45,768
  • 6
  • 62
  • 130
PSR
  • 38,073
  • 36
  • 106
  • 149
19

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

test = test.replace("KP", "");
Reimeus
  • 155,977
  • 14
  • 207
  • 269
7

String is immutable in java so you have to do

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