Short form for Java if statement

2019-01-16 03:16发布

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?

15条回答
霸刀☆藐视天下
2楼-- · 2019-01-16 03:23

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) ...
查看更多
趁早两清
3楼-- · 2019-01-16 03:25

To avoid calling .getName() twice I would use

name = city.getName();
if (name == null) name = "N/A";
查看更多
对你真心纯属浪费
4楼-- · 2019-01-16 03:29

You can write if, else if, else statements in short form. For example:

Boolean isCapital = city.isCapital(); //Object Boolean (not boolean)
String isCapitalName = isCapital == null ? "" : isCapital ? "Capital" : "City";      

This is short form of:

Boolean isCapital = city.isCapital();
String isCapitalName;
if(isCapital == null) {
    isCapitalName = "";
} else if(isCapital) {
    isCapitalName = "Capital";
} else {
    isCapitalName = "City";
}
查看更多
闹够了就滚
5楼-- · 2019-01-16 03:30

You can remove brackets and line breaks.

if (city.getName() != null) name = city.getName(); else name = "N/A";

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();

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";

You can do this in Groovy because if you ask for this condition:

if (city.getName()) {
    //returns true if city.getName() != null
} else {
    //returns false if city.getName() == null
}

So the operator ?: assign the value returned from the condition. In this case, the value of city.getName() if it's not null.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-16 03:31

in java 8:

name = Optional.ofNullable(city.getName()).orElse("N/A")
查看更多
爷的心禁止访问
7楼-- · 2019-01-16 03:34

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;
}
查看更多
登录 后发表回答