Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operators Java

Is there a way to implement this in a ternary operation. I'm very new to that ternary stuff, maybe you could guide me.

if(selection.toLowerCase().equals("produkt"))
     cmdCse.setVisible(true);
else
     cmdCse.setVisible(false);

This one doesn't seem to work.

selection.toLowerCase().equals("produkt")?cmdCse.setVisible(true):cmdCse.setVisible(false);
like image 895
Stefan Sprenger Avatar asked Jan 19 '14 16:01

Stefan Sprenger


2 Answers

In this case, you don't even need a ternary operator:

 cmdCse.setVisible(selection.toLowerCase().equals("produkt"));

Or, cleaner:

 cmdCse.setVisible(selection.equalsIgnoreCase("produkt"));

Your version:

selection.toLowerCase().equals("produkt")? cmdCse.setVisible(true): cmdCse.setVisible(false);

is semantically incorrect: ternary operator should represent alternative assignments, it's not a full replacement for if statements. This is ok:

double wow = x > y? Math.sqrt(y): x;

because you are assigning either x or Math.sqrt(y) to wow, depending on a condition.

My 2cents: use ternary operator only when it makes your program clearer, otherwise you will end up having some undecipherable one-liners.

like image 129
Stefano Sanfilippo Avatar answered Oct 13 '22 21:10

Stefano Sanfilippo


Perhaps

cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
like image 32
Reimeus Avatar answered Oct 13 '22 20:10

Reimeus