Java ternar confusion
here is my code
public class BinarySearch {
public static int binsearch(int key, int[] a)
{
int lo = 0;
int hi = a.length - 1;
while (lo < hi)
{
int mid = (lo + hi) >> 1;
key < a[mid] ? hi = mid : lo = (mid + 1);
}
return lo--;
}
}
I got an error while compiling
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on tokens, Expression expected instead
Syntax error on token "]", delete this token
Syntax error, insert "]" to complete Expression
and if i change '<' to '>' like
key > a[mid] ? hi = mid : lo = (mid + 1);
got a generic error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token ">", -> expected
I am really confused about using the ternary operator in java. in the end this code works fine in C ++
source to share
The compiler is having a hard time parsing your expression because it is being used as an expression expression.
Since the ternary operator is an expression, it should not be used instead of the * operator . Since you want to control the assignment, which is an expression, with a condition, you should use the usual one if
:
if (key < a[mid]) {
hi = mid;
} else {
lo = (mid + 1);
)
* In fact, Java does not allow term expressions to be used as operators. You can work around this problem by wrapping your expression in an assignment or initialization (see demo ), but this will result in code that is difficult to read and understand and should therefore be avoided.
source to share
From the documentation :
The conditional operator has three operand expressions. ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
It is a compile-time error for the second or third operand expression as a void method call.
In other words, the conditional operator cannot be used to do something like this *:
key < a[mid] ? foobar1() : foobar2();
- There is a workaround that uses reflection, but in the end, the brevity of the code doesn't trump readability.
source to share