Xavier F
Xavier F

Reputation: 89

Java ternary operator 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 when 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 '>' as

key > a[mid] ? hi = mid : lo = (mid + 1);

got a total different error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Syntax error on token ">", -> expected

I am really confused about the ternary operator usage in java. after all, this code works fine in c++

Upvotes: 3

Views: 2753

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

The compiler is having hard time parsing your expression because it is used like a statement-expression.

Since ternary operator is an expression, it should not* be used in place of a statement. Since you would like to control the assignment, which is a statement, with the condition, you should use a regular if:

if (key < a[mid]) {
    hi = mid;
} else {
    lo = (mid + 1);
)

* In fact, Java does not allow ternary expressions to be used as statements. You could work around this issue by wrapping your expression in an assignment or an initialization (see demo), but this would result in code that is hard to read and understand, so it should be avoided.

Upvotes: 11

Srini
Srini

Reputation: 1646

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 either the second or the third operand expression to be an invocation of a void method.

In other words, the conditional operator cannot be used to do something like this*:

key < a[mid] ? foobar1() : foobar2();
  • There is a workaround using reflection but at the end of the day, code succinctness does not trump readability.

Upvotes: 0

haley
haley

Reputation: 1175

In this case you should use an if statement.

if(key > a[mid])
    hi = mid;
else
    lo = mid + 1;

This is because the ternary operator is used for when you're setting a variable. For example:

foo = (firstVariable > secondVariable) ? 1 : 0;

(something along those lines).

Upvotes: 1

maskacovnik
maskacovnik

Reputation: 3084

Ternary operator in java works only like this:

x=(a>b?a:b);

This operation puts the larger of a and b
This is not allowed:

a>b?x=a:x=b;

It maybe looks similar, but ternary operator branches in java can contain only value, not assigment


EDIT:
In your case I advice to use if statement

Upvotes: 1

Related Questions