Search code examples
javatalend

handling null pointer exception in talend in OR statement


I have this code. it is the row exception filter in the right hand map of a tMap:

row2.method.equals("Twitter") && (
    row2.last_notified.equals(null) ||
    row2.frequency.equals("Everytime") || 
    (row2.frequency == "Hourly" && TalendDate.diffDate(TalendDate.addDate(row2.last_notified,1,"HH"), TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.getDate("yyyy-MM-dd HH:mm:ss")), "HH") > 0) ||
    (row2.frequency == "Daily" && TalendDate.diffDate(TalendDate.addDate(row2.last_notified,1,"dd"), TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.getDate("yyyy-MM-dd HH:mm:ss")), "dd") > 0)
)

I have a nullPointerException. I know that frequency is not null, as is method. I know that last_notified is null. based on my logic, all rows with "Twitter" as a value with no last_notified should pass. However, it looks like I failed with this.

I understood that OR statements go from left to right. If the first value comes back True, then the OR SHOULD return true? What am I missing?


Solution

  • Regarding

    row2.last_notified.equals(null)
    

    Don't test for null with the equals method as that risks throwing the NPE exception since you'll be attempting to call a method on a null variable. Always use == instead since you're not testing the notified reference's value but rather whether the reference itself is null.

    So do

    row2.last_notified == null
    

    Also regarding

    row2.frequency == "Daily"
    

    It's the exact opposite here as you're comparing Strings wrong -- use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two object references are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.

    Instead do:

    row2.frequency.equals("Daily")