No.
Java requires the expression of a conditional statement has to be of type boolean
, or something automatically convertible to a boolean
; the only type which can be so converted is Boolean
, via unboxing.
Unless you define a method with a meaninglessly short name, you can't do this with fewer characters:
if (n(str)) { // "n()" requires 3 characters
if (str == null) { // " == null" requires 8 characters
// (remove the whitespace if you want to do it in 6...)
But those 5 extra characters save an awful lot of cognitive burden, of wondering "what on earth is n
?!", not to mention the additional characters of defining and/or importing that method. On the other hand, anybody who has written any Java (or, likely, some other language) instantly understands == null
.
str == null
precisely conveys what you're testing for: that the reference is null, as opposed to empty, or convertible to a number whose value is zero, or something else.
== null
also has beneficial compile-time properties, for example that it will stop you using a primitive operand, for example int i = 0; if (i == null) {}
is a compile-time error, because i
is primitive and thus cannot be null
, whereas if (n(i)) {}
would be allowed (provided the formal parameter type is Object
, which you'd want it to be, for maximum reuse), because i
would be boxed.
Java is a reasonably verbose language; there are many things that are more verbose than this. Personally, I wouldn't even notice writing == null
, it is that conditioned into my muscle memory.
Stop worrying, and learn to love the syntax.