3

I have a function public int BinarySearch(int key) which returns -1 when no match is found, else it returns the index of key element in the array , namely, mid. I thought of using ternary operator, while calling this function,

int found = b.BinarySearch(key);
(found < 0) ? System.out.println("not found!") : System.out.println("key element at "+found);

But I am getting syntax errors. I looked up in the internet about this, I saw few examples but my doubt is not clarified.Based on the examples, I think it is because ternary operator can be used for assignment operation only. Please help me clarify this doubt.

Siddhant
  • 626
  • 1
  • 7
  • 20
  • 4
    It can be used for all sorts of expressions, but I don't know if you're allowed to just have an expression as a statement. It probably has to be an assignment or a method call. Also, even if there wasn't a syntax error, this wouldn't work, because `println` is a void-returning method. – user Oct 06 '20 at 15:37
  • 1
    oh okay, I had no idea about return type of println. thankyou – Siddhant Oct 06 '20 at 15:39
  • 1
    Try `System.out.println((found < 0) ? "not found" : "key element at "+found)`. This way you can make use of the value "returned" by the operator. – qwerty Oct 06 '20 at 15:41
  • 1
    I tested this with integer constants instead of the println, the compiler still complains. So this seems to be, in fact, not caused by the void return type. Of course if it actually needs an assignment, then you can't use expressions that come out as void. – kutschkem Oct 06 '20 at 15:43
  • 1
    i Tried what was told by @ap , "System.out.println((found < 0) ? "not found" : "key element at "+found)". This way, it is working fine. Thank you for response. – Siddhant Oct 06 '20 at 15:45
  • 2
    @user Only *some* expressions can be used as statements. They are known as **Expression Statements**, and are defined by [JLS 14.8](https://docs.oracle.com/javase/specs/jls/se15/html/jls-14.html#jls-14.8). – Andreas Oct 06 '20 at 15:58
  • 1
    The targets of a ternary cannot be void methods. Something must be returned. – WJS Oct 06 '20 at 16:27

0 Answers0