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,060
  • 6
  • 35
  • 47

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
  • 697,062
  • 78
  • 1,055
  • 1,465
3

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

file = file.replaceAll("/", "_");
hmjd
  • 117,013
  • 19
  • 199
  • 247
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
  • 203,151
  • 43
  • 392
  • 509
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
  • 6,958
  • 4
  • 41
  • 66
0

You should read about immutable property.

Immutable property

Why are strings immutable in many programming languages?

Community
  • 1
  • 1
Yegoshin Maxim
  • 870
  • 2
  • 20
  • 53