How to use the Ternary Operator in Java
Built in to Java is an operator called the ternary operator.
The ternary operator is essentially a condensed version of an if-else statement that is also capable of returning a value.
In this post, we'll learn how to use the ternary operator in Java.
How to use the ternary operator in Java
As mentioned before, the ternary operator is a conditional operator that is used to evaluate a boolean expression and return a value based on the result of the expression.
Let's first look at a traditional if-else statement:
JAVAint number = 10;
String result = "";
if (number % 2 == 0) {
result = "even";
} else {
result = "odd";
}
System.out.println("The " + number + "number is " + result);
BASHThe number 10 is even
Now let's look at the same code using the ternary operator:
JAVAint number = 10;
String result = number % 2 == 0 ? "even" : "odd";
System.out.println("The number " + number + " is " + result);
BASHThe number 10 is even
As you can see, the ternary operator is a lot more concise than the if-else statement.
Also, notice that the ternary operator returns a value, which is why we can assign the result of the ternary operator to a variable.
How to Nest Ternary Operators
Because ternary operators mimic if-else statements, they can also be nested, though not recommended:
JAVAint number = 11;
String result = number % 2 == 0 ? "divisible by 2" : number % 3 == 0 ? "divisible by 3" : "divisible by neither 2 nor 3";
System.out.println("The number " + number + " is " + result);
BASHThe number 11 is divisible by neither 2 nor 3
It works, but it's not very readable, however you can improve readability by using parentheses:
JAVAint number = 11;
String result = number % 2 == 0 ? "divisible by 2" : (number % 3 == 0 ? "divisible by 3" : "divisible by neither 2 nor 3");
System.out.println("The number " + number + " is " + result);
BASHThe number 11 is divisible by neither 2 nor 3
Conclusion
In this post, we learned how to use the ternary operator in Java.
The ternary operator is a great way to write concise code that can also return a value.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js