Ternary Operator in Java

Ternary operator is a combination of if and else in a single statement.

Format

booleanExpression ? expression1 : expression2

Example

int outputVal = input > 10 ? input*2 : input*5;
 
In the above example, if input > 10, then output = input *2, else output = input *5
 
input = 12 => input > 10 => output = input *2 = 12 * 2 = 24
input = 5 => input < 10 => output = input *5 = 5 * 5 = 25
package com.java.core;

public class TernaryExample {

    public static void printString(String input) {
        System.out.println(input != null ? input : "null String");
    }

    public static int output(int input) {
        int outputVal = input > 10 ? input * 2 : input * 5;
        return outputVal;
    }

    public static void main(String[] args) {
        printString("abc");
        printString(null);
        System.out.println("input:" + 5 + ",output:" + output(5));
        System.out.println("input:" + 12 + ",output:" + output(12));
    }

}
abc
null String
input:5,output:25
input:12,output:24

Related Article

Simple Java Programs asked in Interviews

Leave a Reply

Your email address will not be published. Required fields are marked *