String manipulation in Java Here is the question followed by my working program:


  Given a string, return a version without the first 2 chars. Except
  keep the first char if it is 'a' and keep the second char if it is
  'b'. The string may be any length. Harder than it looks. 

deFront("Hello") → "llo"  
deFront("java") → "va"  
deFront("away") → "aay"



Can this code be improved?

public String deFront(String str) {
    if (str.length() &gt;= 2) {
        char firstCharacter = str.charAt(0);
        char secondCharacter = str.charAt(1);
        if (firstCharacter == 'a' &amp;&amp; secondCharacter == 'b') {
            // donot skip
            return str;
        } else if (firstCharacter == 'a' &amp;&amp; secondCharacter != 'b') {
            // skip first character only
            return str.substring(0, 1) + str.substring(2);
        } else if (firstCharacter != 'a' &amp;&amp; secondCharacter == 'b') {
            // skip second character only
            return str.substring(1);
        } else {
            return str.substring(2);
        }
    } else if (str.length() == 1 &amp;&amp; str.charAt(0) == 'a') {
        return str;
    } else {
        return str;
    }
}
Just recoded it, doing simply what your explanation said 


  Except keep the first char if it is 'a' and keep the second char if
  it is 'b'.


Since a possible deletion of a character will affect indices, we check the second character before we check the first.
The resulting code is much simpler and readable simply because the extracted method deleteCharIfNotEqualTo() does away with some code duplication and at the same time heightens readability of the deFront() method, by explaining what is happening.

public String deFront(String str) {
    StringBuilder builder = new StringBuilder(str);
    deleteCharIfNotEqualTo(builder, 1, 'b');
    deleteCharIfNotEqualTo(builder, 0, 'a');
    return builder.toString();
}

private void deleteCharIfNotEqualTo(StringBuilder builder, int index, char character) {
    if (builder.length() &gt; index &amp;&amp; character != builder.charAt(index)) {
        builder.deleteCharAt(index);
    }
}