Java: Best practice for null check
This question already has an answer here:
If that is needed, why JVM cannot the job by default.
It does! It checks if the value is null, and if not, throws a NullPointerException
. In many cases this is the appropriate behaviour and you do not need to change it.
Normally it's easiest to simply declare variables or methods so that they never return a null. However, sometimes it's unavoidable, like in some existing methods in the API, and some self-created methods and variables need to have a null value set. Personally I recommend avoiding null values whenever possible--it's always best to declare a variable from the start, or have a method return, for example, a -1 instead of a null if a certain operation fails. In general though, if you know a variable or method may have a null value, you should do a null check at the beginning just to be on the safe side.
Hope this helps, and I wish you the best of luck!
链接地址: http://www.djcxy.com/p/13298.html上一篇: 只有属性不为null时才设置属性
下一篇: Java:空检查的最佳实践