Prevent NullPointerException with Java String Equality

One small Java habit that saved me from bugs 👇 Instead of writing: if (str.equals("test")) { // logic } I now write: if ("test".equals(str)) { // logic } 👉 Why this works better? If "str" is null: str.equals("test") → 💥 NullPointerException "test".equals(str) → returns false ✅ (no error) 👉 Because: "test" is a real object, so calling equals() is always safe. 💡 Simple change... but very useful in real projects. Do you follow this pattern? 👇 #Java #CoreJava #Programming #BackendDeveloper #Coding #TechLearning

To view or add a comment, sign in

Explore content categories