As other programming languages, Java also provides ternary operator. The ternary operator is the simple one liner statement of an if-then-else statement. A ternary operator uses ? and : simbles. A simple ternary operator works similar to the if-then-else statement. If any condition evaluates to true then true statement executed else false statement executed. Below is the basic syntax of ternary operator in java:

Advertisement
Syntax of ternary operator
 condition ? trueStatement : falseStatement

Basically, there are 3 parts of statement seprated with ? and : symbols.

  • Condition : First part is the condition section.
  • trueStatement : Second is the code block which executes in case of first part condition goes true.
  • falseStatement : The Third part code block executes if condition results as false.

For an example, if any account exists in application record then complete sign in process for user else open signup form for that user.

#1. Ternary Operator vs If-Else

For example, if you have to compare two variables and provide the output based on the result. Using If-Else you need to write code like below:

The same code can be written in a single line using a ternary operator.

#2. Ternary Operator in Java Example

For example, below example code will return the result as “b is greater” because the value of b is 20 which is greater than the value of a.

#3. Nested Ternary Operator Example

You can also use Ternary operated as nested conditions. For the example, if we compare for greatest value among three integer variables. Then if-else statement will be something like below.

The same can be check with single line code using nested ternary operator. Below is the working example of comparing tree variable values and print which variable have the highest integer value.

Conclusion

In this tutorial, you learned about how to use ternary operator in Java and convert the if-else code in single line statement.

Share.

1 Comment

  1. meenal deshpande on

    hi…
    thx for the great article…
    its very basic.. its help me a lot..
    but i want to ask you about Polymorphism..
    did you have an article about it??
    thx…

Leave A Reply


Exit mobile version