Skip to main content

Java: Ternary Operator

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.

Syntax

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?

wait!

This will ease up the confusion.

if(exp1)
{
    var = exp2
}
else 
{
    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;

        System.out.println(res);
    }
}

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.

Tags
Submitted by arilio666 on October 19, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.