Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operator Limits [duplicate]

Let's say we have following if statement:

int a = 1;
int b = 2;

if(a < b) {
    System.out.println("A is less than B!");
}
else {
    System.out.println("A is greater or equal to B!");
}

I have been wondering that if ternary operator replaces if statement when if statement consists from one line of code in each sub-block (if and else blocks), then why above example is not possible to write like this with ternary operator?

(a < b) ? System.out.println("A is less than B!") : System.out.println("A is greater or equal to B!");
like image 797
Amir Al Avatar asked Mar 15 '14 10:03

Amir Al


People also ask

How to find maximum of two numbers using ternary operator?

Let us write a program to find maximum of two numbers using ternary operator. If we compare syntax of ternary operator with above example, then − First, expression a > b is evaluated, which evaluates to Boolean false as value of variable 'a' is smaller than value of variable 'b'.

What is the ternary operator (?

The ternary operator (? :) consists of three operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned to the variable. It is the only conditional operator that accepts three operands. It can be used instead of the if-else statement. It makes the code much more easy, readable, and shorter.

How to compare syntax of ternary operator with example?

If we compare syntax of ternary operator with above example, then − First, expression a > b is evaluated, which evaluates to Boolean false as value of variable 'a' is smaller than value of variable 'b'. Hence value of variable 'b' i.e. '20' is returned which becomes final result and gets assigned to variable 'max'.

How to assign a ternary operator to a variable in C?

In C programming, we can also assign the expression of the ternary operator to a variable. For example, Here, if the test condition is true, expression1 will be assigned to the variable. Otherwise, expression2 will be assigned. In the above example, the test condition (operator == '+') will always be true.


1 Answers

You can only use ? : for expressions, not statements. Try

System.out.println(a < b ? "A is less than B!" : "A is greater or equal to B!");

Note: this is also shorter/simpler.

like image 187
Peter Lawrey Avatar answered Oct 20 '22 01:10

Peter Lawrey