Why am I getting a StringIndexOutOfBoundsException when I try to replace `\\` with `\`?

java, string

Solution

Use `String.replace` instead of `replaceAll` to avoid it using a regex:

String original = MyConstants.LOCATION_PATH + File.seperator 
    + myObject.getStLocation();
System.out.println(original.replace("\\\\", "\\"));

Personally I wouldn't do it this way though - I'd create MyConstants.LOCATION_PATH_FILE as a `File` and then you could write:

File location = new File(MyConstants.LOCATION_PATH_FILE,
                         myObject.getStLocation());

which will do the right thing automatically.

Problem

I have to replace `\\` with `\` in Java. The code I am using is ``` System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\", "\\") ); ``` But I don't know why it is throwing `StringIndexOutOfBoundsException`. It says `String index out of range: 1` What could be the reason? I guess it is because the first argument `replaceAll` accepts a pattern. What could be the possible solution? Stacktrace ``` Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.charAt(String.java:558) at java.util.regex.Matcher.appendReplacement(Matcher.java:696) at java.util.regex.Matcher.replaceAll(Matcher.java:806) at java.lang.String.replaceAll(String.java:2000) ``` Answer Found asalamon74 posted the code I required, but I don't know why he deleted it. In any case here it is. There is a bug already filed in Java's bug database. (Thanks for this reference, asalamon.) ``` yourString.replaceAll("\\\\", "\\\\"); ``` Amazingly, both search and replace string are the same :) but still it does what I require.

Original source