简体   繁体   中英

Java declare variable in ternary operation. Is it possible?

Say we have some city with String getZIP() method. I want to print value of ZIP or don't print anything if ZIP is null.

I can do it in one line of code with ternary operation:

System.out.print(city.getZIP() == null ? "" : city.getZIP())

The question is: can I do the same without calling .getZIP() twice? Something like:

System.out.print(String zip = city.getZIP() == null ? "" : zip) //syntax error here

Define the variable in a separate line :

String zip = city.getZIP();
System.out.print(zip == null ? "" : zip);

You can assign the value to an existing variable, but not create one inside the ternery condition.

Something like,

String zip; // Created elsewhere but not assigned to city.getZip().
System.out.print(((zip = city.getZIP()) == null) ? "" : zip)

But you can't declare a new variable inside.

I have a completely different solution for you: don't do that .

Do not put methods on your classes that return null as "legit" result.

For example: zip code could / should be its own class. And then you simply declare some singleton instance of ZIP to represent "ZIP code is undefined". And then calling toString on "UnknownZip" ... just gives an empty string for example.

Using null as return value always opens up the chance for NullPointerExceptions.

So - don't do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM