Conditional Expression in Java

| Page Views: 71

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)

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.


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.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:
Ages are Sorted

Result 2 Note we are only considering ascending.

Enter Ages:
Ages are not Sorted

Result 3

Enter Ages:
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.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.


What do You Think

Previous Post Next Post