Bugs

Java String Comparison: Why == Doesn't Work

Using == to compare strings is one of the most common Java mistakes. == compares object references, not string content.


❌ Comparison Bug with ==

public boolean checkRole(String userRole) {
    String requiredRole = new String('admin');
    if (userRole == requiredRole) {  // Always false! Different objects
        return true;
    }
    return false;
}

✅ Fixed with .equals()

public boolean checkRole(String userRole) {
    if ('admin'.equals(userRole)) {  // Content comparison
        return true;
    }
    return false;
}
// Case-insensitive:
// if ('admin'.equalsIgnoreCase(userRole))
💡

Pro tip: Use Objects.equals(a, b) when either operand might be null — it handles null safely without throwing NPE.

Paste this code into LearnCodeGuide

Detect Java vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Java Code →

Related Guides

Java Null Pointer ExceptionJava Array Index Out Of BoundsJavascript Equality Operator Bugs