The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .
The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
The Ternary Operator One of my favourite alternatives to if...else is the ternary operator. Here expressionIfTrue will be evaluated if condition evaluates to true ; otherwise expressionIfFalse will be evaluated.
Use the ternary operator:
name = ((city.getName() == null) ? "N/A" : city.getName());
I think you have the conditions backwards - if it's null, you want the value to be "N/A".
What if city is null? Your code *hits the bed in that case. I'd add another check:
name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());
To avoid calling .getName()
twice I would use
name = city.getName();
if (name == null) name = "N/A";
The way to do it is with ternary operator:
name = city.getName() == null ? city.getName() : "N/A"
However, I believe you have a typo in your code above, and you mean to say:
if (city.getName() != null) ...
The ? : operator in Java
In Java you might write:
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
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