Java Program on Ternary Operator

In this article we will see the use of Ternary operator in Java programming language.

Java Program on Ternary Operator

Ternary Operator:

Ternary operator is one type of conditional operator which makes the use of three operands. It is represented by ? : symbol. Mostly it is used as the replacement of if-else statement at many instances.

Syntax:

variable = (expression_condition) ? expression_True : expression_False;

Where,

  • expression_condition is the first expression and it refers to the condition
  • expression_True is the second expression and it is executed when the first expression/condition is True
  • expression_False is the last expression and it is executed when the first expression/condition is False

Example:

ageĀ  = 21
eligibleAge = 18

String result = (age >= eligibleAge) ? "Eligible to vote" : "Not eligible to vote";

Above statement will check the first condition, as 'age' is greater than 'eligibleAge' means Condition is True. So, first expression will be executed hence the result is 'Eligible to vote'.

Let’s see a program to understand it more clearly.

Program:

import java.util.*;

public class Main
{  
    public static void main(String args[])   
    {  
        //Scanner class object created
        Scanner sc = new Scanner(System.in);
        //an integer varible declared and value initialized as 18
        int eligiblAge = 18;  
        //Asing user to enter age
        System.out.print("Enter your age: ");  
        int age = sc.nextInt();
        //checking condition that person is eligible to vote or not by using Ternary operator
        String result = (age >= eligiblAge) ? "eligible to vote" : "not eligible to vote";
        System.out.println("You are " +  result);  
    }  
}
Output:
Case-1
Enter your age: 27
You are eligible to vote

Case-2
Enter your age: 14
You are not eligible to vote

Note: You can use nested ternary operator as well.

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.