Compiler is forcing you to return the value because it may be possible that you never satisfy the condition for the while loop, hence you don't enter the while loop and return the value.
In that case you won't be having return statement for the method which is supposed to return an int
.
In your case if length of int[] a
is 0, you wont be returning anything as you don't satisfy condition for while loop.
In such scenario, you need to validate the input
and if input does not pass validation check, you can return an exception
. Here, IllegalArgumentException
seems suitable to me, but it totally depends on you that which exception you want to throw.
throw new IllegalArgumentException("Error message");