I know there is a way for writing a Java if
statement in short form.
if (city.getName() != null) {
name = city.getName();
} else {
name=
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";
}
Simple & clear:
String manType = hasMoney() ? "rich" : "poor";
long version:
String manType;
if (hasMoney()) {
manType = "rich";
} else {
manType = "poor";
}
or how I'm using it to be clear for other code readers:
String manType = "poor";
if (hasMoney())
manType = "rich";
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());