Implementing a method that escapes single quotes in a string
I'd suggest a Solution based on regular expressions like this:
import static org.junit.Assert.assertThat;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hamcrest.CoreMatchers;
import org.junit.Test;

public class EscapeQuotesTest {

    Pattern escapedQuotePattern = Pattern.compile(&quot;(\\\\)?(')(')&quot;);

    private String escapeString(String input) {
        Matcher escapedQuote = escapedQuotePattern.matcher(input);
        escapedQuote.find();
        Optional&lt;String&gt; escapeChar = Optional.ofNullable(escapedQuote.group(1));
        String result = String.format(&quot;%s%s\\'%s&quot;, escapeChar.orElse(&quot;&quot;), escapedQuote.group(2), escapedQuote.group(3));
        return result;
    }

    @Test
    public void preseveLeadingBackslash() {
        String input = &quot;\\''&quot;;
        String result = escapeString(input);
        assertThat(&quot; The escape char survived&quot;, result, CoreMatchers.containsString(&quot;\\'\\''&quot;));
    }

    @Test
    public void noLeadingBackslash() {
        String input = &quot;''&quot;;
        String result = escapeString(input);
        assertThat(&quot;no escape char at beginning&quot;, result, CoreMatchers.containsString(&quot;'\\''&quot;));
    }
}