can we use ternary operator just like an if-else statement in every case, where no nesting is required?

Viewed 60

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.

0 Answers
Related