We have this code in our Java 11 practice exam book. What do you think it prints?
public class Hippo {
private static void hippo(short num1, short num2) {
System.out.println("shorts");
}
private static void hippo(int... nums) {
System.out.println("varargs");
}
private void hippo(long num1, long num2) {
System.out.println("longs");
}
private void hippo(int num1, int num2) {
System.out.println("nums");
}
public static void main(String... args) {
hippo(1, 5);
} }
Reasoning it through, we know, it doesn’t print longs or nums because the main() is static and therefore we can’t be calling an instance methods. The answer is varargs because we have ints. This seems nice and reasonable.
I then ran the same code in Java 17 and it doesn’t compile!
% java17 Hippo.java
Hippo.java:15: error: non-static method hippo(int,int) cannot be referenced from a static context
hippo(1, 5);
^
1 error
error: compilation failed
i do agree that hippo(int, int) can’t be called. I was surprised at the behavior where it no longer compiles. If I remove the two instance variables, Java still prints varargs like I was expecting.