Java is littered with statements like:
if(cage.getChicken() != null) { dinner = cage.getChicken(); } else { dinner = getFreeRangeChicken(); }
Which takes two calls to getChicken()
before the returned object can be assigned to dinner
.
This could also be written in one line like so:
dinner = cage.getChicken() != null? cage.getChicken() : getFreeRangeChicken();
But alas there are still two calls to getChicken()
.
Of course we could assign a local variable then use the ternary operator again to assign it if it is not null, but this is two lines and not so pretty:
FutureMeal chicken = cage.getChicken(); dinner = chicken != null? chicken : getFreeRangeChicken();
So is there any way to say:
Variable var = some value if some value is not null OR some other value;
And I guess I'm just talking syntax here, after the code is compiled it probably doesn't make much difference how the code was written in a performance sense.
As this is such common code it'd be great to have a one-liner to write it.
Do any other languages have this feature?
To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter. It returns true as the passed object is null.
Use the ISNULL function with the IF statement when you want to test whether the value of a variable is the null value. This is the only way to test for the null value since null cannot be equal to any value, including itself. The syntax is: IF ISNULL ( expression ) ...
The String class in the System namespace provides the IsNullOrEmpty() method to check if a string is null or an empty string(""). This is a handy method to validate user input.
In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator. Let's take an example to understand how we can use the isNull() method or comparison operator for null check of Java object.
Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.
You can use the result variable as your temporary, like this:
dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();
This, however, is hard to read.
Same principle as Loki's answer but shorter. Just keep in mind that shorter doesn't automatically mean better.
dinner = Optional.ofNullable(cage.getChicken()) .orElse(getFreerangeChicken());
Note: This usage of Optional
is explicitly discouraged by the architects of the JDK and the designers of the Optional feature. You are allocating a fresh object and immediately throwing it away every time. But on the other hand it can be quite readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With