Java "" Operator for Checking Null - What Is It? (Not Ternary!)

Java ? Operator for checking null - What is it? (Not Ternary!)

The original idea comes from groovy. It was proposed for Java 7 as part of Project Coin: https://wiki.openjdk.java.net/display/Coin/2009+Proposals+TOC (Elvis and Other Null-Safe Operators), but hasn't been accepted yet.

The related Elvis operator ?: was proposed to make x ?: y shorthand for x != null ? x : y, especially useful when x is a complex expression.

Java : check for null in setter using ternary

It should be:

public void setMake(String Make) {
this.Make = Make == null ? "" : Make;
}

You want to assign the result of the ternary conditional operator to your instance variable.

And when you want to refer to the Make passed to the method, you should write Make, not this.Make (which is the instance variable).

Is there a ternary assignment operator in Java?

I disagree with all other answers. They require special functionality from specific versions by importing structures from the standard library, or obscure calls that works in this specific case, and all in all just hides the simplicity of what you're trying to do.

Keep it simple (KISS). Don't introduce more complexity and concepts when you don't need them. You're refactoring another developers code, which means this is a project where someone else will probably be reading your code later on. So keep it dead simple.

String name = xService.getName(xID);
xModel.setName(name != null ? name : "");

This is more readable than all other examples and doesn't require intimate knowledge of the standard library and its API.

Is there a ?. operator for Java to perform null pointer checking?

There is no ?. operator in Java, so, as Hari notes, you have to do things the "long winded" way. However, one could argue that this is a good thing, as it discourages the use of nulls.

For example, in OP's code, why are you setting val to null if a or it's child is not there? Let's assume that this is a function and val gets returned. This is a code smell: it just pushes the requirement for yet another null check to users of your code. It becomes an endless cycle of null checks, completely cluttering the code and confusing the logic, because maintenance programmers often can't tell if this is legitimate logic, or a paranoid former programmer is quietly ignoring errors. Don't mimic PHP!. Quoting from that excellent rant:

"When faced with either doing something nonsensical or aborting with an error, it (PHP) will do something nonsensical."

PHP makes a horrible design choice. It is far better to abort with an error than do something nonsensical.

Instead, you should be asking questions like:

  1. What does it mean for a to be null? Is this a programming error? If so, throw some RuntimeException / IllegalArgumentException. If this is critical code and you "can't fail", at least log that you are papering over something fishy, so maybe it will get fixed.
  2. What if a.child.getValue() itself returns null? How will my caller tell the difference between that null and the "a or child is null" null? They can't.
  3. If there is a good default value, use it. If you are using a Collection or Array, don't pass null to mean "empty". Pass a Collections.emptyXXX(), e.g. an emptyList, or an empty array. Instead of setting a String to null, consider setting it to the empty string "". BTW, this makes your hashCode(), equals(), and compareTo() much simpler!
  4. Use the Null Object Pattern.. If a is an instance of a Foo, define a static final Foo.NULL which does have a child whose value is itself something "nullish" - either null or "".

Sometimes you really can't do any of these things. There are valid reasons for arguments to be null, or you must allow for backwards compatibility with a previous bad design or 3rd party library. IMO, this should be rare, and you should document what happens. And maybe you should return something other than null (or 0) to reflect this. For example

/**
countPeople
@param node null means the foobar can't connect to the database,
@return Foobar.ERR_NO_DB if node is null
*/

In OP's example, it looks like a may be some sort of XML node, and the Java XML interfaces are huge and creating a good NULL object for one of them would be a huge undertaking. (Hmm, maybe a good little open source project?). However, in that case, you will likely be calling a.child.getValue() a lot. Write a little utility function to handle this and handle the nulls. Instead of long winded null checks everywhere, at least they are encapsulated in a few utility methods. DRY. And, arguably the fact that the checks are long winded, encouraged you to do a better design. So the lack of the ?. operator was a good thing, right? :-)

Can I null-check in-line?

I think you remember the elvis operator ( http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000047.html ) which was rejected ( https://blogs.oracle.com/darcy/entry/project_coin_final_five ) from project coin.

However, the jakarta commons have nvl-like functions such as http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringUtils.html#defaultString(java.lang.String) Even though these functions are not standard java, they end up in most programs as dependecy of some library.

The problem you have is a common when you design a function with a valid null result: You have to document and handle the special case everywhere. I can pretty much guarantee you that someone will mess this up in maintenance, resulting in spurious null pointer exceptions. That's why i would, in general, recommend designs that don't return null.

Odd Java ternary behavior when assigning value. What is Java doing behind the scenes for this to happen?

When you do this:

Long result = bool ? intVal : longVal

This expression is returning a long and, when bool is false it tries to unboxe null to a Long value to fit the result variable and throws a NPE.

When you do this:

Long result = bool ? Long.valueOf(intVal) : longVal

This expression is already returning Long then there is no need for unboxing and the null value is successfully assigned to the result variable.

Reference:

As discussed in the comments section, to better understand why does this happen, check the following sections of the JLS:

  • Section 5.6.2: Binary Numeric Promotion
  • Section 15.25: Conditional Operator ? :

Java trim() : Cleanest way to check null string before trimming?

I like the idea from @Sebastiaan van den Broek but would prefer not to use the library and therefore look up its implementation:

// Trim
//-----------------------------------------------------------------------
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling {@code null} by returning
* {@code null}.</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #strip(String)}.</p>
*
* <p>To trim your choice of characters, use the
* {@link #strip(String, String)} methods.</p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, {@code null} if null String input
*/
public static String trim(final String str) {
return str == null ? null : str.trim();
}

From my point of view there is no better way to implement it. Using Optionals is not an option. Therefore, the original solution idea in the question is confirmed.

Is it good to give null a meaning along with two Boolean value to represent ternary balue in filtering?

Use of a ternary value is well established in filtering applications. More often, you'll see the options named ACCEPT, DENY, and NEUTRAL. This is extremely useful in short-circuiting filter chains. However, these mechanisms don't use null to represent NEUTRAL.

Using a 3-valued enum instead gives you more utility.

Values can have methods. The implementation can be different for each value, or it could be a common implementation that works sort of like the Visitor pattern. If you use Boolean and null, you can't provide custom methods, and even if you could extend Boolean, you can't extend null.

You can use enum values as keys in maps more readily than null, which isn't accepted by many Map implementations. This can be useful for keying handlers by status.

You can use enum values in switch statements, and the compiler helps to ensure that you've covered all the options. If you fail to handle true, false, and null in a cascade of if-else-if-else, the compiler won't notice.

Finally, you should use the @FunctionalInterface annotation on your functional interfaces. It will cause the compiler to complain if you carelessly add another abstract method, or do anything else that makes your type ineligible for use functionally.



Related Topics



Leave a reply



Submit