MrMins MrMins - 6 days ago 5
Java Question

What a simple search method should return any value is correct

I'm studying Java and I have a very simple question.

I have a method as such:

public int search(int[] A, int b) {
// Code...
}


This method should return the position of the value element specified with
b
into the array
A
.

But, following the standards, what should be returned when the
b
is not found inside the array
A
(or when A is empty)?

Answer

Return -1.

For a simple array indexed from 0, -1 is not a valid index, and so is a safe value to return to indicate "value not found" since it cannot be confused with an actual index. That is a common convention across multiple languages (not only Java).

If the array is empty, then you could still just return -1 (because it is still true that the value cannot be found in the array). Alternatively, you could throw an exception if you have a reason to handle the case of an empty array differently than that of a non-empty array. If not, then just return -1 (no need to overcomplicate code without a reason).