Question:
Today I was at a Java interview and fell for the if
.
The challenge was to write a method that returns the second largest number from the input array. Failed on the if
while checking the data. My implementation was like this:
public int getSecondMaxNumber(int[] numbers) {
if (numbers == null || numbers.length < 2) {
throw new IllegalArgumentException();
}
// далее логика получения второго макс. числа
}
To my great surprise, it turned out that I had made a gross mistake. The program logic should be enclosed in an else
block, that is, like this:
public int getSecondMaxNumber(int[] numbers) {
if (numbers == null || numbers.length < 2) {
throw new IllegalArgumentException();
}
else {
// именно здесь логика получения второго макс. числа
}
}
Why write all the rest of the code in the else
block if the execution flow of this method is interrupted when an exception is thrown?
Similarly, as it turned out, and in the case when, instead of throwing an exception, return
simply indicated. In general, there should always be an else
after the if
else
.
As far as I understood from the words of the technical manager, in the case of the else
JVM performs some kind of optimization. I would like to learn more about this moment – what kind of optimization and where can I read more about it?
Answer:
In addition to @ VladD's answer: I compiled the following class using java 8:
public class IfElse {
public int getSecondMaxNumber1(int[] numbers) {
if (numbers == null || numbers.length < 2) {
throw new IllegalArgumentException();
}
return numbers[1];
}
public int getSecondMaxNumber2(int[] numbers) {
if (numbers == null || numbers.length < 2) {
throw new IllegalArgumentException();
} else {
return numbers[1];
}
}
}
You can see that the bytecode of the methods is exactly the same:
$ javap -c IfElse.class
Compiled from "IfElse.java"
public class IfElse {
public IfElse();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public int getSecondMaxNumber1(int[]);
Code:
0: aload_1
1: ifnull 10
4: aload_1
5: arraylength
6: iconst_2
7: if_icmpge 18
10: new #2 // class java/lang/IllegalArgumentException
13: dup
14: invokespecial #3 // Method java/lang/IllegalArgumentException."<init>":()V
17: athrow
18: aload_1
19: iconst_1
20: iaload
21: ireturn
public int getSecondMaxNumber2(int[]);
Code:
0: aload_1
1: ifnull 10
4: aload_1
5: arraylength
6: iconst_2
7: if_icmpge 18
10: new #2 // class java/lang/IllegalArgumentException
13: dup
14: invokespecial #3 // Method java/lang/IllegalArgumentException."<init>":()V
17: athrow
18: aload_1
19: iconst_1
20: iaload
21: ireturn
}