1

Is it possible to convert the below java code using ternary operator:

if (x > 0) {
    a = 100;
    b = 100;
} else {
    a = 1;
    b = 1;
}
1
  • you can do it with two ternary operators. Commented Jan 16, 2020 at 8:07

2 Answers 2

5

You can write:

a = b = x > 0 ? 100 : 1;

but only because you assign the same value to a and b.

In the general case, you'd need a separate ternary conditional operator for each variable you wish to assign to:

a = x > 0 ? 100 : 1;
b = x > 0 ? 100 : 1;
Sign up to request clarification or add additional context in comments.

Comments

2

You can handle this with one ternary expression:

a = x > 0 ? 100 : 1;
b = a;

This works because the assignment logic for both a and b happens to be the same. If that were not the case, we would need two separate ternary expressions:

a = x > 0 ? 100 : 1;
b = x > 0 ? 100 : 1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.