0

I have written a below routine in Java, I need to know that the code is Null Pointer Safe or not:

public class TRM_Fields {
    public static String returnActualValue(String Staffing_Event,
            String CurrentValue, String PriorValue) {
        String returnValue;
        returnValue = null;

        if ("TRM".equalsIgnoreCase(Staffing_Event) && CurrentValue == null
                && PriorValue != null && !"".equalsIgnoreCase(PriorValue)) {
            returnValue = PriorValue;
        } else {
            returnValue = CurrentValue;
        }
        return returnValue;
    }
}

Any of the parameter Staffing_Event, CurrentValue and PriorValue may be null.

If it is not Null Pointer Safe what should I do to achieve that?

2
  • It seems to be safe, "".equalsIgnoreCase(null) do not throw a NullPointerException Commented Jun 19, 2014 at 9:08
  • Why are you still not simply referring to the documentation? I told you off for this over a year ago. Commented Aug 11, 2014 at 14:17

1 Answer 1

3

Your method is safe. You are correctly using "constantString".equals(someObject) to ensure a null-safe comparison.

Some other comments:

  • Your method is hard to read because you are using TitleCase for Java variables, when they should be camelCase.

  • You only have two possible return values. So you can simplify your method as follows:

    public static String returnActualValue(String staffingEvent,
            String currentValue, String priorValue) {
    
        if ("TRM".equalsIgnoreCase(staffingEvent) && currentValue == null
                && priorValue != null && !"".equalsIgnoreCase(priorValue)) {
            return priorValue;
        } else {
            return currentValue;
        }
    }
    

    Note that the else construct isn't necessary, so it's a matter of style whether you include that structure or simply have return currentValue;.

Sign up to request clarification or add additional context in comments.

7 Comments

Ok I will take care of camelCase.
I am writing this code in Talend.So I need to return outside of the if and else otherwise it gives error.
@AbdulManaf Interesting. I'm not familiar with Talend - what error do you get, out of interest? It seems odd that semantically identical code should be rejected.
This method must return a result of type String
@AbdulManaf Maybe you typed it wrong somehow? My code above compiles just fine with a standard Java compiler.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.