javaif-statementstatements

Does order of the states in the if statement matter?


from line 5 on my code which is,

if (i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k')

Does the order of statements matter? I was wondering because

when I assign str = "yak123ya"

(i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k') works perfectly fine but

(str.charAt(i) == 'y' && str.charAt(i + 2) == 'k' && i + 2 < str.length()) causes

error

StringIndexOutOfBoundsException: String index out of range: 8 (line:5)

public String stringYak(String str) {
  String result = "";

  for (int i = 0; i < str.length(); i++) {
    if (i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k') {
      i += 2;
    } else {
      result += str.charAt(i);
    }
  }
  return result;
}

Thank you!!


Solution

  • The expressions are evaluated left to right, with short-circuiting. That means when an expression a && b is evaluated, and a evaluates to false, the whole expression evaluates to false without executing b.

    In this case, when i = 6, i + 2 < str.length() is false, and therefore the charAt(6) is not executed (and therefore not throwing an exception).