MrMins MrMins - 5 months ago 42
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
into the array

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


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).