Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Ternary with no return. (For method calling)

I was wondering if it was possible to do a ternary operation but without returning anything.

If it's not possible in Java is it possible in other languages, if so which ones apply?

name.isChecked() ? name.setChecked(true):name.setChecked(false); 
like image 654
TylerKinkade Avatar asked Feb 26 '12 05:02

TylerKinkade


People also ask

How do I return nothing in ternary operator?

A ternary operator doesn't have a do nothing option for either the true or false path since the entire ternary command returns a value and so both paths must set a value. The “do nothing” value will depend on what value you want the ternary operator to return to indicate “do nothing”.

Can we call method in ternary operator in Java?

In essence, your answer says: "Yes, it's possible to use the ternary operator without assigning a variable. All you have to do is -- assign a variable."

Does ternary operator return?

The Java ternary operator provides an abbreviated syntax to evaluate a true or false condition, and return a value based on the Boolean result.

Can ternary operator have 3 conditions?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


1 Answers

No, you can't. But what's the point of this over an if-else statement? Are you really trying to save 7 characters?

if (name.isChecked()) {     name.setChecked(true); } else {     name.setChecked(false); } 

or if you prefer bad style:

if (name.isChecked()) name.setChecked(true); else name.setChecked(false); 

Never mind the fact that you can just do (in this case):

name.setChecked(name.isChecked()); 

The point of the ternary or "conditional" operator is to introduce conditionals into an expression. In other words, this:

int max = a > b ? a : b; 

is meant to be shorthand for this:

int max; if ( a > b ) {     max = a; } else {     max = b; } 

If there is no value being produced, the conditional operator is not a shortcut.

like image 188
Mark Peters Avatar answered Sep 23 '22 07:09

Mark Peters