Reputation: 131
why does this work:
public String delDel(String str) {
if(str.length() >= 4 && str.substring(1,4).equals("del")){
String front = str.substring(0,1);
String back = str.substring(4, str.length());
return front + back;
}
else{
return str;
}
}
and this not work:
public String delDel(String str) {
if((str.substring(1,4).equals("del")) && str.length() >= 4){
String front = str.substring(0,1);
String back = str.substring(4, str.length());
return front + back;
}
else{
return str;
}
}
if you notice the difference between the first and second is that str.length() is before the rest of the condition in the first and it is the last condition in the second.
Upvotes: 0
Views: 58
Reputation: 178263
The difference demonstrates short-circuit evaluation.
In Java, with the boolean operator &&
, the second operand won't be evaluated if the first operand is false
. This difference is crucial when the second operand being able to be evaluated depends on the first condition being true
.
First code example:
if(str.length() >= 4 && str.substring(1,4).equals("del")){
The second part will only be evaluated if the length is 4. If the length wasn't at least 4, then substring
would fail with a StringIndexOutOfBoundsException
. But it can't, because if the length is at least 4, then the call is valid.
Second code example:
if((str.substring(1,4).equals("del")) && str.length() >= 4){
Now the call to substring
will be evaluated always, regardless of length, and thus can throw StringIndexOutOfBoundsException
.
Even the JLS, Section 15.23, has this to say about the subject:
The conditional-and operator && is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
Additionally, the condition-or operator ||
works similarly, according to the JLS, Section 15.24:
The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.
Upvotes: 4
Reputation: 726619
The reason the second condition may not work is that when the str
is shorter than 4
characters, you will see a failure in the second condition. The first condition, however, guards against this, because &&
operator would not evaluate substr
when the length is less than 4
.
Upvotes: 1