2

Possible Duplicate:
Hints for java.lang.String.replace problem?
Using string.replace() in Java

Why "/" does not replaced by "_" ?

public static void main(String[] args) throws IOException {
    String file = "A/B";
    file.replaceAll("/", "_");
    System.out.println(file);
}
Community
  • 1
  • 1
Mehdi
  • 2,160
  • 6
  • 36
  • 53

6 Answers6

5

Because instances of java.lang.String are immutable*. replaceAll returns the correct string, but your program throws it away. Change your program as follows to correct the issue:

file = file.replaceAll("/", "_");


* That's a fancy way of saying "non-changeable": once a string instance "A/B" is created, there are no methods that you could call on it to change that value.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

You need to store the result of the file.replaceAll() call as String instances are immutable:

file = file.replaceAll("/", "_");
hmjd
  • 120,187
  • 20
  • 207
  • 252
1

You have to assign the result of the replaceAll:

public static void main(String[] args) throws IOException {
    String file = "A/B";
    String newFile = file.replaceAll("/", "_");
    System.out.println(newFile);
}
TapaGeuR
  • 76
  • 6
1
file.replaceAll("/", "_");

Since, String in Java is immutable, so any method of String class, not just replaceAll, does not modify the existing String.. Rather they create a new String and return that.. So you should re-assign the returned string to the file..

file = file.replaceAll("/", "_");
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

Look carefully at String.replaceAll javadoc: it returns a String.

Method like this won't modifies their parameter. So you need to write:

String file = "A/B";
file = file.replaceAll("/", "_");
yves amsellem
  • 7,106
  • 5
  • 44
  • 68
0

You should read about immutable property.

Immutable property

Why are strings immutable in many programming languages?

Community
  • 1
  • 1
Yegoshin Maxim
  • 872
  • 2
  • 21
  • 54