Ternary operator to check if string is empty

There is a variable String userId;

Determine whether it is null, if it is null, assign it to an empty string; otherwise, it is unchanged;

write yes with an if condition

if (null == userId) {
    userId = "";
}


Want to use the ternary operator to write, common mistakes

userId == null ? "" : userId;

This is wrong and will report Type mismatch: cannot convert from null to boolean


Correct spelling:

userId = (userId == null) ? "" : userId;


The advantage of the ternary operator compared to the if statement is that it beautifies the code and makes the code more concise;

The disadvantage is that you need to be familiar with the syntax of the ternary operator to understand it, which is not as logical as the if statement, easy to read and understand;

Each has advantages and disadvantages, use as needed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325472367&siteId=291194637