Cannot invoke equals(boolean) on the primitive type boolean

I want to check equality of first and last two characters of a string so i have written condition like

if (str.length() >= 4
            && ((str.startsWith(str.substring(0, 2))).equals(str.endsWith(str
                    .substring(str.length() - 3, str.length() - 1)))))

but I am getting error as Cannot invoke equals(boolean) on the primitive type boolean

so what is the root cause?

Jon Skeet
people
quotationmark

I want to check equality of first and last two characters of a string

That's not what you're doing though. You're using startsWith and endsWith - you're asking whether a string starts with its own first two characters, and whether it ends with some portion of the string near the end, and then trying to compare the results of those comparisons... except that you're trying to compare two boolean values with equals instead of ==, which isn't going to work either.

You just want substring and equals here - but your substring is incorrect too, in that you have an off-by-one error for finding the last two characters. I would personally split this up for simplicity:

if (str.length() > 4) {
    String start = str.substring(0, 2);
    // If you don't specify an end point, it'll be "the rest of the string"
    // which is what you want.
    String end = str.substring(str.length() - 2);
    if (start.equals(end)) {
        ...
    }
}

people

See more on this question at Stackoverflow