292

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?

0xCursor
  • 2,242
  • 4
  • 15
  • 33
Makky
  • 17,117
  • 17
  • 63
  • 86

17 Answers17

555

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());
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 16
    +1, though you have redundant parentheses. I would have written: `name = city.getName() == null ? "N/A" : city.getName();` – Andres F. Jan 17 '12 at 17:02
  • 28
    A matter of style and taste: I like to make the grouping of the boolean clause clear. – duffymo Jan 17 '12 at 17:06
  • 6
    Whatever - I used DeMorgan's theorem and got what you needed. No need to edit, as long as you express the logic correctly. – duffymo Jan 17 '12 at 17:08
  • 1
    The logic is correct. The only possible flaw with this answer is if city is mutable. – emory Jan 17 '12 at 18:16
  • 3
    FYI the outer parenthesis are unnecessary. You can just do `name = city.getName()==null ? "N/A" : city.getName()` – Steve Kuo Jan 17 '12 at 19:50
  • Yeah, I know. Like I said above, it's a matter of taste. It doesn't enhance or diminish the correctness of the answer. – duffymo Jan 17 '12 at 20:42
  • @duffmo I'm not worried about threads - it's not my code. Only "1000 ways AAAAAAAAH" knows the details - like whether getName is a standard getter method that always returns the same value - in which case your code is perfect. – emory Jan 17 '12 at 21:17
  • 4
    Won't `String cityName = city.getName();` throw a `NullPointerException` if `city == null`? I'd therefore say your middle solution is definitely the best (PS and I approve of the 'unnecessary' parentheses! People need to remember that 99% of coding is communicating with other people (and your future self), not the compiler - otherwise we'd use c!) – Alex Apr 25 '13 at 01:27
  • Is there a way to include "else if" in this statement? – Mohsin Falak Jul 02 '20 at 19:56
  • No. Is it too much to ask that you refer to a language reference? – duffymo Jul 02 '20 at 20:44
48

To avoid calling .getName() twice I would use

name = city.getName();
if (name == null) name = "N/A";
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 2
    In a multi user system with a mutable city, there could be an intervening `city.setName(null)`. Your answer neatly handles that. – emory Jan 17 '12 at 18:14
35

The ? : operator in Java

In Java you might write:

if (a > b) {
  max = a;
}
else {
  max = b;
}

Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:

max = (a > b) ? a : b;

(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.

35

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) ...
Sam Goldberg
  • 6,711
  • 8
  • 52
  • 85
33

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;
}
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
25

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.

IgniteCoders
  • 4,834
  • 3
  • 44
  • 62
22

in java 8:

name = Optional.ofNullable(city.getName()).orElse("N/A")
digitebs
  • 834
  • 8
  • 10
11

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";
}
dreamer
  • 317
  • 1
  • 13
OctopusSD
  • 147
  • 1
  • 4
11
name = (city.getName() != null) ? city.getName() : "N/A";
Alessio Koci
  • 1,103
  • 11
  • 24
shift66
  • 11,760
  • 13
  • 50
  • 83
7

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);
Waqas Qayum
  • 69
  • 1
  • 3
4

Use org.apache.commons.lang3.StringUtils:

name = StringUtils.defaultString(city.getName(), "N/A");
Paul Rambags
  • 639
  • 7
  • 5
4

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";
Vasile Doe
  • 1,674
  • 1
  • 24
  • 40
4

You could make it much easier this way :

name = city.getName() == null ? city.getName() : "N/A"
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 01 '21 at 10:41
  • This will throw a NullPointerException everytime. `city.getName()` and `"N/A"` should be inverted. Ternary operators work like : `boolean_expression ? execute_if_true : execute_if_false` [https://www.baeldung.com/java-ternary-operator](documentation) – Kyysel Aug 07 '23 at 10:04
3
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:

  1. condition is in the parenthesis followed by a question mark. That's why I write (city.getName() == null)?. Here the question mark is right after the condition. Easy to see/read/guess even!
  2. value left of colon (:) 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

RamenChef
  • 5,557
  • 11
  • 31
  • 43
0

In Java 8+ you have 2 solution. With short if statement:

Objects.nonNull(city.getName())? city.getName(): "N/A";

Better solution in your case is use Optional:

Optional.ofNullable(city)
            .map(City::getName)
            .orElse("N/A");
Victor1125
  • 642
  • 5
  • 16
-1

One line, avoiding second call to method (and creation of additional Optional instance):

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

partly based on source code of standard Java classes

user16320675
  • 135
  • 1
  • 3
  • 9
-5
name = city.getName()!=null?city.getName():"N/A"
Sarkhan
  • 1,281
  • 1
  • 11
  • 33
Shadow
  • 6,161
  • 3
  • 20
  • 14
  • 5
    Instead of just posting some code you would help OP more by explaining the technique. How does it work, why does it work? – Zabuzard Aug 08 '17 at 23:53
  • 2
    Putting spaces around your operators make it much easier to read & maintain. – geowar Sep 20 '17 at 10:41