Search code examples
javamethodsbooleanreturn

return statement in boolean method


I do not understand what I should return. My method returns false if the last time it goes through the for-loop it is false. If the last time is true than it returns true. But I want it to return false regardless of where the false occurred.

    public class test {
        public static void main(String[] args) {
            int number = 4;
            int[] intArray = {4, 8, 12, 16};
            System.out.println(allMultipleOf(intArray, number));
        }
        public static boolean allMultipleOf(int[] ary, int n){
            boolean a = true;
            for(int i = 0; i < ary.length; i++){
                if(ary[i] % n == 0){
                    a = true;
                    //System.out.println(a);
                    break;
                } else {
                    a = false;
                }
            }
    }
        return a; //what should I return
}

Solution

  • You can return false early from the method, if we reached the end without returning false, then return true:

    public static boolean allMultipleOf(int[] ary, int n) {
        for (int i = 0; i < ary.length; i++) {
            if (ary[i] % n != 0) {
                return false;
            }
        }
        return true;
    }