Strings-Remove Duplicates

import java.util.*;
public class Main {
public static String duplicate(String str, String ans,int j){
if(j>=str.length())
return (ans);
char c=str.charAt(j);
if(c==str.charAt(j+1)){
ans=ans+str.charAt(j);
return duplicate(str,ans,j+2);}
else{
ans= ans+str.charAt(j);
return duplicate(str,ans,j+1);}

    }


public static void main(String args[]) {
	try{

Scanner sc=new Scanner(System.in);
String str=sc.nextLine();

    System.out.println(duplicate(str," ",0));
}catch(Exception e){System.out.println(e);}}

}what is problem with my code

There are two problems with your code here:
1] It shows Runtime Error. You are trying to access str.substring(j + 1) even when j is str.length() - 1;
2] Even if you correct this Runtime Error logic by Out of Bounds checking prior to calling your substring function, the logic of your code isn’t correct. Take the example:- aaabc and think how to proceed with it.

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.