Suppose I have a method called withoutX
that, when given a string, removes first and last letters of the string if they are x.
My code is:
public String withoutX(String str) {
if(str.length()>0 && str.substring(0,1).equals("x")) {
str = str.substring(1);
}
if(str.length()>0 && str.substring(str.length()-1).equals("x")) {
str = str.substring(0,str.length()-1);
}
return str;
}
Why does this return the empty string ("") when str = "x"? Wouldn't the case when str = "x" fail after the first if
statement because str = str.substring(1)
references an index that is out of bounds (the max. index of str = "x" is 0)?