Understanding parameters
You're lucky that the task is to count the occurrences of a single character. Your code instead looks as if it would count the occurrences of a string.
(@RolandIllig's answer)
I think that's a good start to understanding why defining a method with the right parameters is important. The original task is to count character occurrences, so it's likely the method should look something like this in Java:
public static int countOccurrence(String input, char value) { /* ... */ }
// to call
countOccurrence("hello", 'l');
In that case, your implementation will then change slightly to become:
public static int countOccurrence(String input, char value) {
return input.length() - input.replace(String.valueOf(value), "").length();
}
By making it clear what your parameters are, we can now care about how to explain your logic.
Explaining logic vs implementation
Similar to what was pointed out in @Josiah's answer, have a think about how you will explain your logic, and then reflect if that was as elegant as saying "loop through each character and count the number of matches for my 'value' character".
It's easy to commingle short code as elegant code, but as you have to deal with more complex logic in larger code bases, you will learn that you have to care about how it can be explained rather than how short it reads.
It is not as elegant to understand a simple 'count-the-occurrence' method as having to get the length of the input string, and subtract that with a copy that does not have the matching 'value' character.
Performance
To be frank, you really should not have to care about performance for a simple method as this, as that reeks of micro-optimization. However, if you are interested in comparing your solution and a simple for
loop, you can roughly think in terms of the memory required by your code as it goes along.
Your solution already knows about its input, and it needs to create a copy of that input, albeit shorter. A for
loop requires an additional int
to count. It doesn't require making that extra copy.
On the other hand, the stream-able way has more 'plumbing' underneath, but its advantage come in terms of a more declarative way of approach, instead of the imperative approaches we traditionally have.
for
loop might yield more code, but functionality-wise, it would be more to the point. Maybe this is what your teacher meant. \$\endgroup\$$cnt = $sky =~ tr/*/*/; # count the stars in $sky
\$\endgroup\$