Makky Makky - 1 year ago 139
Java Question

Short form for Java If statement

I know there is a way for writing java if statement in short form

if (city.getName() != null) {
name = city.getName();
} else {

does anyone know how to write short form for above 5 lines into one line...

Answer Source

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

I'll follow along with the (very good) example below:

name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download