title: replace() and replaceAll() in Java
body: <p>The following code uses the <code>replace()</code> method of the <code>String</code> class in Java.</p>
  
  <pre><code>String a = "abc/xyz";
  System.out.println(a.replace("/", "\\"));
  </code></pre>
  
  <p><code>/</code> in the given String <code>a</code> is being replaced with <code>\</code>.</p>
  
  <p>The same thing is wrong, if we use the <code>replaceAll()</code> method as follows.</p>
  
  <pre><code>System.out.println(a.replaceAll("/", "\\"));
  </code></pre>
  
  <p>It causes the exception <code>java.lang.StringIndexOutOfBoundsException</code> to be thrown. It requires two additional backslashes <code>\</code> like the following, since <code>replaceAll()</code> uses a regex which is not the case with the <code>replace()</code> method.</p>
  
  <pre><code>System.out.println(a.replaceAll("/", "\\\\"));
  </code></pre>
  
  <p>The only question is why does this method when used with only two slashes like this <code>a.replaceAll("/", "\\")</code> throw <code>java.lang.StringIndexOutOfBoundsException</code>?</p>
  
  <hr>
  
  <p>The <code>split()</code> method on the other hand initially issues a waring <code>Invalid regular expression: Unexpected internal error</code> (I'm using NetBeans 6.9.1).</p>
  
  <pre><code>String b="abc\\xyz";
  System.out.println(b.split("\\")[0]+b.split("\\")[1]); //Issues a warning as specified.
  </code></pre>
  
  <p>An attempt to run this causes the exception <code>java.util.regex.PatternSyntaxException</code> to be thrown.</p>
  
  <p>Since it uses a regex like <code>replaceAll()</code>, it requires four back slashes.</p>
  
  <pre><code>System.out.println(b.split("\\\\")[0]+b.split("\\\\")[1]);
  </code></pre>
  
  <p>Why does <code>a.replaceAll("/", "\\\\");</code> as in the preceding case not issue such a warning or such a run time exception, even though it has an invalid pattern?</p>