Java ternary operator on simple binary search problem

The conditional operator can only be used as part of an expression. An expression cannot stand on its own, but needs to be part of a statement. Assigning a variable is a statement. Computing a value and not storing it, is not. Convert the expression to an statement:

int ans = (nums[middle] < target) ? (left = middle + 1) : (right = middle - 1);

Becomes:

if (nums[middle] < target) {
  left = middle + 1;
} else {
  right = middle - 1;
}

If you want to save a few key strokes:

if (nums[middle] < target) left = middle + 1;
else right = middle - 1;

Relevant links to the JLS:

  • JLS 14.5 Statements
  • JLS 14.8 Expression Statements
  • JLS 15.25 Conditional Operator