Java: Ternary Operator

Profile picture for user arilio666

So in a java programming language if I say there is an alternative to the if-else statement would you believe it? Yes, there is an alternative called the ternary operator which operates just like the if-else statement.

Ternary Operator, consumes less memory so it is ideal to use this operator and also the code looks neat than the normal if-else. We can use this operator in the place of if-else or even in the switch statement too.


var = exp1 ? exp2 : exp3

So the syntax can be pretty confusing so let me explain. Here inside var, we are doing (if exp1 condition is true then exp2 else exp3)

got it?


This will ease up the confusion.

    var = exp2
    var = exp3

Realtime Example

public class Test
    public static void main(String[] args)
        int val1 = 10, val2 = 20, val3, val4 = 10, val5;
        int res = (val2 > val1) ? (val2 * val1) : val1;


Output: 200

So here as you can see the res variable has the following condition. 

if val2 is greater than val1 then multiply val2 with val1 else print val1.