-2

I was wondering how this code would look like with the ternary operator

if (a) {
    // pass
} else {
    b(); 
}

We got no(thing) code to execute when a is true but in case a is false there is some code b() which is then executed.

So we write that:

a ? : b();

But I am not sure if that is correct when you let the code for true empty or if you have to replace it with something. Actually I never use the ternary operator but we were asked to do so.

budi
  • 5,533
  • 6
  • 46
  • 73

3 Answers3

7

That's not what the conditional operator is for... it's not to execute one statement or another, it's to evaluate one expression or another, and make that the result of the expression.

You should write your code as:

if (!a) {
    b();
}

Actually I never use the ternary operator but we were asked to do so.

If you were asked to do so for this particular situation, then I would be very wary of whoever was asking you to do so. My guess is that it was actually not quite this situation...

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
2

If you had tried this code, then you would get compiler errors because the ternary operator expects expressions, not statements. The true section doesn't even have an expression or a statement. If b() returns void, then the false section is a statement, not an expression. If b() returns something, then it can be considered an expression and it would be ok.

If you have statements to execute, and you don't have to choose an expression value, then choose if/else over the ternary operator. Your first if/else can be simplified to:

if (!a)
{
    b();
}
rgettman
  • 167,281
  • 27
  • 248
  • 326
  • @Downvoter Please share how you think this answer can be improved. – rgettman Nov 11 '15 at 22:01
  • For me your description does not make much sense, i.e. _and the false section is a statement, not an expression_ - in the `false` branch a method is called - and if it does not return `void` that's perfectly legal. For me your description sounds like calling methods inside the ternary operator is not allowed - which is not true. But maybe I just misunderstood... – tomse Nov 11 '15 at 22:26
  • @tomse I had assumed it returns `void` because nothing is being assigned, but I have clarified my answer. – rgettman Nov 11 '15 at 22:33
  • 1
    ...OK, removed the downvote – tomse Nov 11 '15 at 22:37
1

This isn't possible. Taken from the official Oracle Docs:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

ConditionalExpression:
    ConditionalOrExpression
    ConditionalOrExpression ? Expression : ConditionalExpression

The definition of "ternary" is "Composed of 3 parts". If you want only one possible evaluation of your condition, you will just have to use an if statement.

Smittey
  • 2,410
  • 10
  • 28
  • 33