Skip to content
Advertisement

Ternary Operators Java [duplicate]

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

JavaScript

This one doesn’t seem to work.

JavaScript

Advertisement

Answer

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

JavaScript

Or, cleaner:

JavaScript

Your version:

JavaScript

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

JavaScript

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.

Advertisement