Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Calling equals() on String literal or Known object

Sumit Rawal answered on May 14, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers


Calling equals() on String literal or Known object

0

For a long time while writing Java code, I used to invoke equals method like below:

if(givenString.equals("YES")){

// do something.

}

It’s natural because it reads better but its not safe. You can prevent a potential NullPointerException by calling equals() on String literal, if one object is happen to be Sring literal or on known object e.g.

"TRUE".equals(givenBoolean)

"YES".equals(givenString)

if you do reverse e.g. givenBoolean.equals(“YES”) then it will throw NullPointerException if givenBoolean is null, but if you follow this idiom then it will just return false without throwing any NPE. This is a much better code, its safe and robust. In fact this is one of the popular ways to avoid NullPointerException in Java.

Popularity 1/10 Helpfulness 1/10 Language javascript
Source: Grepper
Link to this answer
Share Copy Link
Contributed on May 14 2023
Sumit Rawal
0 Answers  Avg Quality 2/10


X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
X
Grepper Account Login Required

Oops, You will need to install Grepper and log-in to perform this action.