CodingBat warm up: conditionally prepending "not" to a string I solved this CodingBat problem:


  Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. Note: use .equals() to compare 2 strings.


notString("candy") → "not candy"
notString("x") → "not x"
notString("not bad") → "not bad"


Here is the solution I came up with:

public String notString(String str) {
  if(str.indexOf("not") == 0){
    return str;
  }
  return "not " + str;
}


I was wondering how it compared to their solution:


public String notString(String str) {
  if (str.length() &gt;= 3 &amp;&amp; str.substring(0, 3).equals("not")) {
    return str;
  }

  return "not " + str;
}



Obviously neither is "wrong" but I was just wondering (in the long run) which has better syntax / more efficient code?
It should be obvious which strategy is better. Suppose you are given a very long string. Do you really want to search the entire string for "not", then realize that the match is irrelevant because it doesn't occur at the beginning?  Or would you rather just examine the first three characters of the string?

Of course, the most straightforward solution uses .startsWith():

public String notString(String str) {
    return str.startsWith("not") ? str : "not " + str;
}


I don't know why they gave a hint to use .equals(). It's also a bit unclear how a string like "notary" should be handled. Treat these tutorial-challenge sites with some suspicion.