Java: How to check for null pointers efficiently

前端 未结 14 1802
清歌不尽
清歌不尽 2020-12-03 01:17

There are some patterns for checking whether a parameter to a method has been given a null value.

First, the classic one. It is common in self-made code

14条回答
  •  被撕碎了的回忆
    2020-12-03 01:59

    The first option is the easiest one and also is the most clear.

    It's not common in Java, but in C and C++ where the = operator can be included in a expression in the if statement and therefore lead to errors, it's often recommended to switch places between the variable and the constant like this:

    if (NULL == variable) {
       ...
    }
    

    instead of:

    if (variable == NULL) {
       ...
    }
    

    preventing errors of the type:

    if (variable = NULL) { // Assignment!
       ...
    }
    

    If you make the change, the compiler will find that kind of errors for you.

提交回复
热议问题