DEV Community

Cover image for Java Programming intelliJ Basics (Ternary operator)
Deeksha V
Deeksha V

Posted on

Java Programming intelliJ Basics (Ternary operator)

Ternary operator:

Also known as conditional operator. It is a shorthand operator for if-else statement. it has three operands.

Syntax:
Operand1 ? Operand2 : Operand3

The question mark (?) here represents to evaluate the condition. it acts as a delimiter between the condition and the expressions.
Here condition is an operand 1 and expressions are operand 2 and operand 3. The colon symbol (:) will test, if the first operand (operand 1) is true and returns the operand 2, otherwise it returns operand 3.

Example: Ternary operator with an If-else statement

public class SecondClass {

    public static void main(String[] args) 
    {
     int age = 20;

        boolean TheAgeis = (age == 20) ? true : false;

        if(age == 20) {

            System.out.println("Is an Adult");
        } 
        else {
            System.out.println("Still a kid");
        }
Enter fullscreen mode Exit fullscreen mode

In the above code, at first the variable age is set to 20, next checking whether the condition is true, if the condition that is age is equal to 20 is true, it returns the output as Is an Adult otherwise it returns Still a kid. The above code can be simplified as follows.

Example: Ternary operator without an If-else statement

public class SecondClass {

    public static void main(String[] args) 
    {
     int age = 20;

        boolean TheAgeis = (age == 20) ? true : false;

        String s = (TheAgeis) ? "Is an Adult" : "Still a kid";

        System.out.println(s);
    }
}
Enter fullscreen mode Exit fullscreen mode

Here after the condition is checked and if it results true, the statement to be printed, will be stored in the String variable s, which will display the output.

Top comments (0)