title: Java - "String index out of range" exception
body: <p>I wrote this little function just for practice, but an exception ("String index out of range: 29") is thrown and I don't know why...</p>
  
  <p>(I know this isn't the best way to write this function and can I use regular expressions.)</p>
  
  <p>This is the code:</p>
  
  <pre><code>public String retString(String x) 
  {
      int j=0;
      int i=0;
      StringBuffer y = new StringBuffer(x);
  
  try
  {
  
  
      while ( y.charAt(i) != '\0' )
      {
          if (y.charAt(i) != ' ')
          {
              y.setCharAt(j, y.charAt(i));
              i++;
              j++;
          }
          else
          {
              y.setCharAt(j, y.charAt(i));
              i++;
              j++;
              while (y.charAt(i) == ' ')
                  i++;
          }           
      }
      y.setCharAt(j,'\0');
  
  
  
  }
  finally 
  {
  
      System.out.println("lalalalololo " );
  }
  
      return y.toString();
  
  
  }
  </code></pre>