Short form for Java if statement

JavaIf StatementTernary Operator

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

To avoid calling .getName() twice I would use

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

Solution 3 - Java

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) ...

Solution 4 - Java

> 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.

Solution 5 - Java

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

Solution 6 - Java

in java 8:

name = Optional.ofNullable(city.getName()).orElse("N/A")

Solution 7 - Java

> 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.

Solution 8 - Java

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

Solution 9 - Java

name = (city.getName() != null) ? city.getName() : "N/A";

Solution 10 - Java

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

Solution 11 - Java

Use org.apache.commons.lang3.StringUtils:

name = StringUtils.defaultString(city.getName(), "N/A");

Solution 12 - Java

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

Solution 13 - Java

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

Solution 14 - Java

You could make it much easier this way :

name = city.getName() == null ? city.getName() : "N/A"

Solution 15 - Java

name = city.getName()!=null?city.getName():"N/A"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMakkyView Question on Stackoverflow
Solution 1 - JavaduffymoView Answer on Stackoverflow
Solution 2 - JavaPeter LawreyView Answer on Stackoverflow
Solution 3 - JavaSam GoldbergView Answer on Stackoverflow
Solution 4 - JavaReza Baradaran GazorisangiView Answer on Stackoverflow
Solution 5 - JavaSuragchView Answer on Stackoverflow
Solution 6 - JavadigitebsView Answer on Stackoverflow
Solution 7 - JavaIgniteCodersView Answer on Stackoverflow
Solution 8 - JavaOctopusSDView Answer on Stackoverflow
Solution 9 - Javashift66View Answer on Stackoverflow
Solution 10 - JavaWaqas QayumView Answer on Stackoverflow
Solution 11 - JavaPaul RambagsView Answer on Stackoverflow
Solution 12 - JavaArafe Zawad SajidView Answer on Stackoverflow
Solution 13 - JavaVasile DoeView Answer on Stackoverflow
Solution 14 - JavaOsama AlzahraniView Answer on Stackoverflow
Solution 15 - JavaShadowView Answer on Stackoverflow