came here to say the main trick has also been possible for C and Java. The C version has already been pointed out in sibling comments, while Java one requires more "tricks" in terms of bash substitution.
I remember I built a such java "interpreter" during my first year of university (10+ years ago! time flies fast...) because the initial intro/101 courses always had one-off programs and the main language was java.
although I no longer have the original source(s) it was something like
///usr/bin/env javac $0 && java ${0%%.java}; exit; # /
since it's quite simple, I even had a funny named wrapper called "java-script" (pun intended) in my $PATH so that I could just write
//usr/bin/env java-script # /
at the top. As you can see I already confused fellow students with the great naming scheme I used :)
There is a talk called "Java for Small Coding Tasks" by the author of Core Java: https://www.youtube.com/watch?v=04wFgshWMdA
Apparently, this is the way to do it:
I don't do Java. As one comment on the video said, 'This presentation is the epitome of the old saying: "When your only tool is a hammer, every problem looks like a nail"'