4 ms·
I like the clever use of the "java prog.java" style. I don't know how many folks know, although its been there for a bit, that you no longer have to specifical
by whartung 2y ago
I like the clever use of the "java prog.java" style.
I don't know how many folks know, although its been there for a bit, that you no longer have to specifically compile single file java programs.
You can just run them with with "java prog.java".
(Honestly, I haven't used the technique myself, still old school -- even with silly small x.java tests and such. Muscle memory and all that.)
- grishka 2y agoI do it a lot. These single-file programs can be called Java scripts when run without compilation.
- apantel 2y agoI wonder what could be done with Java script…
- bionsystem 2y agoSounds like a name that could have some success. Given that the logo for Java is a cup of coffee, maybe we could also call it "Coffee script".
- mbreese 2y agoCan you add a shebang line and have it truly be a script? I do self executing JARs with a bash stub/header all the time, but haven’t tried with this.
- grishka 2y agoSadly you can't, Java doesn't support comments starting with # $ ./shebang.java ./shebang.java:1: error: illegal character: '#' #!/usr/bin/java ^ ./shebang.java:1: error: class, interface, enum, or record expected #!/usr/bin/java ^ 2 errors error: compilation failed Self-executable jars though, that's an interesting idea. No reason why it can't work, zip archives are read from the end, you can put anything in the beginning, including "#!/usr/bin/java -jar"
- spullara 2y agothis has worked since the beginning but i don't think many people know about it
- jnellis 2y agoI believe you can use shebang since java 11 but you can't have the filename extension be .java.
- grishka 2y agoIt turns out you indeed can: https://news.ycombinator.com/item?id=40912444 https://news.ycombinator.com/item?id=40912444
- mbreese 2y agoFor the self executing JAR, I normally add a bash/shell stub for the header that ends with java -jar $0 The rest of it sets up the environment (JAVA_OPTS, -Xmx, etc).
- metadat 2y agoHow do you run a Java program without compilation?
- tpoacher 2y agothough, in theory java has jshell for java-based shell scripts specifically
- oftenwrong 2y agoYou can run multi-file source-code programs as of JDK 22: https://openjdk.org/jeps/458 https://openjdk.org/jeps/458