Interesting change in calling methods in Java 17

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.

6 thoughts on “Interesting change in calling methods in Java 17

  1. Is there any Video Tutorials or Course specially for 1z0-819 or 1z0-829?

  2. I took the liberty to report it using your sample code. I hope you don’t mind. I didn’t find an appropriate place to credit you for finding it, I’m sorry. I think it is important to do so because it is:

    1) a change of behavior first and foremost
    2) it is somehow not compliant with the rules and logic

    I played a bit and it seems the varargs have something to do with it. It is what makes the method different and allow it to exist. Was it a static method with two int parameters, the compiler would have complained on all versions. But the compiler failing to recognize there is a static method to be called from a static context is the real issue at hand for me. So even if it was intentional, I think it is a problem that it tries to call the instance method rather than printing an error having two methods that resemble each other in such a way is not allowed.
    Also it might have been a bug that it was compiling all along.

    You can check it out here https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8289277

    Regards,
    Georgi

  3. Georgi: Thank you! I didn’t have time to log it. (I put on my list to look into how to report a bug in the JDK and hadn’t gotten to it.) I appreciate that you did so now I no longer need to :).

    I don’t need credit. The key is that someone reported it!

Leave a Reply

Your email address will not be published.