1.

How Do You Avoid Nullpointerexception, While Comparing Two Strings In Java?

Answer»

Since when compared to null, equals return false and doesn't throw NullPointerException, you can use this property to avoid NPE while using comparing String. Suppose you have a known String "abc" and you are comparing with an unknown String VARIABLE str, then you should call equals as "abc".equals(str), this will not throw Exception in thread Main: java.lang.NullPointerException, even if str is null. On the other HAND, if you call str.equals("abc"), it will throw NPE. So be careful with this. By the way this is ONE of the Java coding best PRACTICES, which Java developer should follow, while using equals() method.

Since when compared to null, equals return false and doesn't throw NullPointerException, you can use this property to avoid NPE while using comparing String. Suppose you have a known String "abc" and you are comparing with an unknown String variable str, then you should call equals as "abc".equals(str), this will not throw Exception in thread Main: java.lang.NullPointerException, even if str is null. On the other hand, if you call str.equals("abc"), it will throw NPE. So be careful with this. By the way this is one of the Java coding best practices, which Java developer should follow, while using equals() method.



Discussion

No Comment Found