2

I was wondring what the best way to check if we have a valid reference in java. I know that this syntax works, but its a mouth full.

if (myObj == null) {
  // Do something knowing we have an object
}

I'm coming from some other languages that allow you to just check a pointer like in c++.

char* prt = null;
if (ptr) {
  // We know we have a valid c-string 
}

Is there any equivocate or similar syntax in java? I would be okay using compiler extensions or a preprocessor.

Follow up before. Before some one jumps in a starts talking about why I should just use the java syntax because you can forget an = sign please don't.

if (myObj = null) 

Will be caught by the compiler/linter.

Charlie OConor
  • 857
  • 1
  • 9
  • 18
  • Also there a quite a few values that would be considered "invalid" in other languages. Such as `0` or `false` or `""`. In Java you have to define exactly what is considered valid yourself. – ST-DDT Nov 07 '17 at 16:03
  • 2
    `null` is idiomatic and makes for easy reading. The fact that C uses `0x0` is implementation detail IMO. – StuartLC Nov 07 '17 at 16:06
  • 2
    this will help you : https://stackoverflow.com/a/2707333/2724879 – Yamen Nassif Nov 07 '17 at 16:11
  • 2
    @Basti `myObject.equals(null)` could never return `true` -- it would NPE. – slim Nov 07 '17 at 16:22
  • 2
    @slim "could never" -> "should never". A badly overwritten `equals` method could allow `null`. I for example saw a JSON lib (can't remember which one) which said that JSON value `"null"` is equal to `null` ... sadly. – Tom Nov 07 '17 at 16:31

3 Answers3

6

Alas Java does not have an implicit conversion of the analogue of a nullptr_t or a pointer type to bool, so you have to use the somewhat more long-winded notation

if (myObj == null)

whereas in C++ we can write

if (myObj)

In this respect, Java is less terse, and arguably clearer.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
5

There is no shortcut syntax for dealing with null checks in Java, not even a null coalesce or null propagation operators available in other languages. There are no user-defined conversion operators either, so you wouldn't be able to use the C++ idiom that lets you write loops on expressions returning objects, e.g. while (cin >> x) { ... }.

However, a powerful alternative exists in Java 8 to avoid null checks altogether: wrap your nullable objects in Optional<T>, and use its methods to hide null checks.

Here is a short example:

String s = "Hello";
Optional<String> os = Optional.ofNullable(s);
os.ifPresent(x -> { System.out.println(x); });

The above prints "Hello". If you set s to null, the code would print nothing.

Oracle's article on using Optional<T>.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Great if there's an API between the `Optional` being initiated, and its consumer calling its methods. But don't use `Optional.ofNullable(x).ifPresent(...)` when `if(x==null) { ... }` will do. – slim Nov 07 '17 at 16:14
  • @slim Ah, of course not! I don't like an idea of swatting flies with a sledgehammer, no matter how efficient it may be at killing the flies. – Sergey Kalinichenko Nov 07 '17 at 16:16
2
if(x == null) {
    doSomething();
}

... is the general idiom in Java. Java's designers made the decision not to allow treating non-boolean variables as implicit "truthy" values.

Another common idiom is to use x == null in a ternary statement:

return x == null ? "not found" : x;

Or to use a standard method to throw an exception early on nulls:

Objects.requireNonNull(x);

More generally, try to adopt a programming style in which you never expect null to be passed, and therefore don't have to code for the possibility.

On non-public APIs, since you never pass a null, you never need to test for null (if a NullPointerException occurs, whoever passed the null can take responsibility for the mess themselves).

In public APIs, it may be a courtesy to the caller to validate non-nulls at the point they are passed, but it's by no means essential in every case.

A reasonable goal is to always expect inputs to be non-null, and to never return a null (since Java 8, use Optional instead if necessary, or adopt the Null Object Pattern).

slim
  • 40,215
  • 13
  • 94
  • 127