I know there is a way for writing a Java if
statement in short form.
if (city.getName() != null) {
name = city.getName();
} else {
name="N/A";
}
Does anyone know how to write the short form for the above 5 lines into one line?
I know there is a way for writing a Java if
statement in short form.
if (city.getName() != null) {
name = city.getName();
} else {
name="N/A";
}
Does anyone know how to write the short form for the above 5 lines into one line?
The way to do it is with ternary operator:
However, I believe you have a typo in your code above, and you mean to say:
To avoid calling
.getName()
twice I would useYou can write
if, else if, else
statements in short form. For example:This is short form of:
Syntax:
So in your code you can do like this:
EXTRA: for curious
In some languages based in
JAVA
likeGroovy
, you can use this syntax:You can do this in
Groovy
because if you ask for this condition:So the operator
?:
assign the value returned from the condition. In this case, the value ofcity.getName()
if it's notnull
.in java 8:
I'm always forgeting how to use the
?:
ternary operator. This supplemental answer is a quick reminder. It is shorthand forif-then-else
.where
()
holds theif
?
meansthen
:
meanselse
It is the same as