Why this code is not working

import java.util.;
public class dup
{
public static void duplicates(String str,int index)
{
if(index==str.length())
{
System.out.println(str);
return;
}
if(str.charAt(index)==str.charAt(index+1) && (index+1)!=str.length())
{
String res=str.substring(0,index)+"
"+str.substring(index);
duplicates(res, index+2);
}
else
duplicates(str, index+1);

}
public static void main(String[] args)
{
   duplicates("hello", 0);

}

}

Hi Ashish,
Your code will go out of bounds as array index will go till 6. Since strings are immutable (i.e. no modification is allowed) I urge you to use stringbuilder to return your answer.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.