I know there is a way for writing a Java if
statement in short form.
if (city.getName() != null) {
name = city.getName();
} else {
name=
name = ( (city.getName() == null)? "N/A" : city.getName() );
firstly the condition (city.getName() == null)
is checked. If yes, then "N/A"
is assigned to name or simply name="N/A"
or else the value from city.getName()
is assigned to name, i.e. name=city.getName()
.
Things to look out here:
(city.getName() == null)?
. Here the question mark is right after the condition. Easy to see/read/guess even!:
) and value right of colon
(a) value left of colon is assigned when condition is true, else the value right of colon is assigned to the variable. here's a reference: http://www.cafeaulait.org/course/week2/43.html
in java 8:
name = Optional.ofNullable(city.getName()).orElse("N/A")
here is one line code
name = (city.getName() != null) ? city.getName() : "N/A";
here is example how it work, run below code in js file and understand the result. This ("Data" != null)
is condition as we do in normal if()
and "Data"
is statement when this condition became true. this " : "
act as else and "N/A"
is statement for else condition. Hope this help you to understand the logic.
name = ("Data" != null) ? "Data" : "N/A";
console.log(name);
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) ...
1. You can remove brackets and line breaks.
if (city.getName() != null) name = city.getName(); else name = "N/A";
2. You can use ?: operators in java.
Syntax:
Variable = Condition ? BlockTrue : BlockElse;
So in your code you can do like this:
name = city.getName() == null ? "N/A" : city.getName();
3. Assign condition result for Boolean
boolean hasName = city.getName() != null;
EXTRA: for curious
In some languages based in JAVA
like Groovy
, you can use this syntax:
name = city.getName() ?: "N/A";
The operator ?:
assign the value returned from the variable which we are asking for. In this case, the value of city.getName()
if it's not null
.
I'm always forgeting how to use the ?:
ternary operator. This supplemental answer is a quick reminder. It is shorthand for if-then-else
.
myVariable = (testCondition) ? someValue : anotherValue;
where
()
holds the if
?
means then
:
means else
It is the same as
if (testCondition) {
myVariable = someValue;
} else {
myVariable = anotherValue;
}