Question

The question is:

Complete the method occursMoreTimes based on the requirements in its comment. 
/** 
*Returns true if the number of times val1 occurs in the array is strictly greater 
*than the number of times val2 occurs in the array. Otherwise, return false. 
*If you wish, you can call the findNumberOf method you wrote above. 
**/ 

My answer was this:

public boolean occursMoreTimes(int[] arr, int val1, int val2){
    if(findNumberOf(arr, val1) > findNumberOf(arr, val2)){
        return true
    }
    else {return false;
    }
}

But the answer key declared an int for the method call I wrote inside the if statement, like this:

public boolean occursMoreTimes(int[] arr, int val1, int val2){
    int countVal1 = findNumberOf(arr, val1);
    int countVal2 = findNumberOf(arr, val2);
        if(countVal1 > countVal2){
            return true
        }
        else {return false;
        }
}

Would my answer work fine? Is there an advantage to declaring a method call as an int?

Was it helpful?

Solution 2

The two are equivalent. In your first example, the compiler creates two temporary ints on your behalf.

OTHER TIPS

The phrase declaring a method call as an int isn't really correct.

What the solution did was declare just a regular variable of type int to store the return value of the method findNumberOf().

In your example, there is really no advantage to declaring a separate int for findNumberOf()s return value.

Scenarios in which it could be advantageous are:

  1. You need to reference those values multiple times throughout the function. Thus you are saving yourself multiple calls to the same method as well as code space (the name most likely being shorter than a call to the method).

  2. You can give the return value a specific name and thus increase code readability.

It all depends on the situation. And in your case it makes no difference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top