Today I was at a Java interview and was dropped on an if .
The task was to write a method that returns the second largest number from the input array. It fell on the if when checking data. My implementation was:
public int getSecondMaxNumber(int[] numbers) { if (numbers == null || numbers.length < 2) { throw new IllegalArgumentException(); } // далее логика получения второго макс. числа } To my great surprise, it turned out that I made a gross mistake. The program logic should be enclosed in an else block, that is, as follows:
public int getSecondMaxNumber(int[] numbers) { if (numbers == null || numbers.length < 2) { throw new IllegalArgumentException(); } else { // именно здесь логика получения второго макс. числа } } Why do you need to write the rest of the code in the else block, if the flow of this method is interrupted while generating an exception?
Similarly, as it turned out, in the case when, instead of generating an exception, simply indicate return . And in general, after the if there should always be else .
As far as I understood from the words of the technical manager, in the case of the else JVM performs some optimization. I would like to know more about this point - what optimization and where can I read more about it?