简体   繁体   中英

Java: String index out of range: -4

i got an error "String index out of range: -4" heres my code below

if (WHEREClause.substring((WHEREClause.length() - 4)) == "AND ") {
    WHEREClause = WHEREClause.substring(0, (WHEREClause.length() - 4)); }

the value of WHERECLAUSE IS => "arSLC_CODE=13 AND "

and if i display "WHEREClause.substring((WHEREClause.length() - 4))" from the code i get this => "AND "

so it looks like if("AND " == "AND ")
{
...i go inside here
}

but instead i got an error "String index out of range: -4" and can't get inside the if statement. please help still new to this

When comparing strings use the .equals instead of == . == is usually used only when comparing references or memory, while .equals is used when to see if they contain the same content

Firstly, Alex Tănăsescu is right, use .equals to compare string content.

Secondly, it looks like WHEREClause attribute may contain an empty string. Are you sure that the exception is throwing inside if block? I'm convinced that it appears earlier in this peace of code:

WHEREClause.substring((WHEREClause.length() - 4))

Just check if the string is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM