1

Is there a shorter way to check if a string / object is null then?

    String str = someMethodThatReturnsStringOrNull(someOthreObject);
    if(str == null) { System.out.println("Empty"); }

like JS style for example:

    if(str) { System.out.println("Empty"); }
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159

1 Answers1

10

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 1
    Replicating the JS version of `if(str)` in Java would be a lot more than a null check. `false`, `undefined`, `NaN`, `0`, `""`, and `"false"` all return false in JavaScript, as well. – Compass Nov 08 '18 at 22:08
  • 1
    @Compass that's exactly the point I am making in the paragraph with "precisely conveys". `== null` means 1 exact thing. – Andy Turner Nov 08 '18 at 22:09
  • 1
    I agree with that statement, I just don't know how else to describe the issue with the fact that the provided JavaScript "equivalent" of not-null is in fact not a not-null check and there is an explicit version. In fact, JS' explicit version of null-check is actually longer than Java's: `if(str === null)` – Compass Nov 08 '18 at 22:12