Conditional Expression in Java


A conditional expression evaluates an expression based on a given condition.

They are used normally to assign a value to a variable that is restricted by a certain condition.

For example if age is greater than 17, then adult otherwise child.

if(age > 17)
{
    person="Adult";
}else{
    person="Child";
}

You can shorten that using a conditional expression:

person = (age > 17) ? "Adult" : "Child";

How conditional Expressions work

Conditional Expressions simplify one condition if-else statements. They allow you write short and concise code.

They are of the following syntax:

boolean-expression ? expression1 : expression2;

In the above, the result will be expression1 if the boolean-expression evaluates to true, otherwise the result becomes expression2.

In Conditional Expressions, the symbols ? and : have to appear together. They are called Conditional Operator.

Conditional Operators are also called Ternary Operator. This is because they use three operands.

Example

Let's write a simple example determine if items are sorted or not.

import java.util.Scanner;

public class MrConditionalExp {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter Ages: ");
        int age1 = input.nextInt();
        int age2 = input.nextInt();
        int age3 = input.nextInt();
        System.out.println((age1 < age2 && age2 < age3) ? "Ages are Sorted(ASC)" : "Ages are not Sorted");

    }
}

Result 1

Enter Ages:
24
46
55
Ages are Sorted

Result 2 Note we are only considering ascending.

Enter Ages:
65
54
23
Ages are not Sorted

Result 3

Enter Ages:
52
56
51
Ages are not Sorted

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post