Explain Codes LogoExplain Codes Logo

Short form for Java if statement

java
best-practices
ternary-operator
null-checks
Nikita BarsukovbyNikita Barsukov·Sep 22, 2024
TLDR

To create a concise representation of an if-else statement in Java, use the ternary operator ?:. This operator allows you to choose between two expressions based on the result of a boolean condition.

Example, or I wager ten quatloos on the newbie:

int smallest = (x < y) ? x : y; // Decide whether x or y is our 'newly-crowned champion of the tiny numbers'

The beautiful translation-follows this rhetoric:

int smallest; // We've got an arena ready for our contestants if (x < y) { smallest = x; // x takes the crown } else { smallest = y; // y grabs the glory }

It's perfect for one-liners or when aiming for efficient code.

Best practices using ternary operator

Null-dodge dance

While dancing the ternary operator, null values might get under your feet and lead to a NullPointerException. Always make sure to check for null values when using the ternary operator.

Readability rocks!

​Though the ternary operator may tempt you with its brevity, remember, readability still rocks! For the greater good of your future self and fellow devs, use it when the condition and results are simple and intuitive.

Testing for our future

Upon refactoring your verbose if-else blocks to a one-line ternary operator, celebrate by testing it heartily. Confirm that the refactored code lives up to the original if-else's functionality, and break out the cookies!

Deeper dive - Advanced techniques

Unfurling nested ternaries

If you have multiple conditions, like in a game of whack-a-mole, you could nest ternaries. Be cautious as they might lose some clarity faster than a politician loses credibility:

int trafficLight = (color.equals("red")) ? 0 : (color.equals("yellow")) ? 1 : 2; // What's the color, mate?

The null knight

We may not have a null-coalescing operator in Java (like we do in some other languages), but a ternary can serve pretty well:

String username = (userInput != null) ? userInput : "defaultUser"; // Who are you? DefaultUser has entered the chat!

Optimizing loops

Think about using a ternary within loops for setting a peculiarly perky preference:

for (int i = 0; i < 10; i++) { results[i] = (i % 2 == 0) ? "even" : "odd"; // Meet my sibling arrays, Even Steven and Odd Todd! }