1

I want to be able to execute java one liners like in python and php.

something like:

java "System.out.println("hello world");"

from within the terminal in linux or cmd in windows

EDIT: Java is a compiled lang. Got it. Can I compile and execute on the fly? Say to a temp file then have it executed? without using jshell

AK_
  • 1,879
  • 4
  • 21
  • 30
  • 1
    java is a compiled language. – OldProgrammer Dec 15 '21 at 17:11
  • 1
    You can execute jshell, [as described here](https://stackoverflow.com/questions/46739870/how-to-execute-java-jshell-command-as-inline-from-shell-or-windows-commandline) – Andy Turner Dec 15 '21 at 17:12
  • There's also REPL, which might be related to jshell (it looks like just an older name for jshell : https://docs.oracle.com/javase/10/jshell/introduction-jshell.htm ) Googling for "java repl" turns up some interesting links, not just jshell ones. – markspace Dec 15 '21 at 17:21
  • Does this answer your question? [How to execute java jshell command as inline from shell or windows commandLine](https://stackoverflow.com/questions/46739870/how-to-execute-java-jshell-command-as-inline-from-shell-or-windows-commandline) – bradley101 Dec 15 '21 at 17:22
  • Probably not what you're looking for but perhaps an acceptable compromise: [How to launch JavaFX source code file from command line?](https://stackoverflow.com/questions/67446229/how-to-launch-javafx-source-code-file-from-command-line) – Abra Dec 15 '21 at 18:20

1 Answers1

3

Starting with Java11, you can run java directly with source files as well, e.g. java MyClass.java

So, in theory, you can do something like this (in bash):

echo 'public class TmpClass{ public static void main(String[] args){System.out.println("Hello World");}}' > /tmp/TmpClass.java && java /tmp/TmpClass.java

Not elegant in any way, and probably not much useful either, but i guess it can be done.

To make it a bit less verbose on the command line, you can create a simple bash script runjava.sh and invoke it as

$ runjava.sh 'System.out.println("Hello World");'
Hello World

runjava.sh:

#!/bin/bash

# inject given line inside the main method of a temp class
read -d '' tmpclass <<EOF
public class TmpClass{
  public static void main(String[] args) throws Exception {
    $@
  }
}
EOF

tmpfile=/tmp/TmpClass.java

# write generated source code to a temporary file
echo $tmpclass > $tmpfile

# execute the source file directly (requires Java11+)
java $tmpfile

# delete the temporary file
rm $tmpfile

jshell would probably be a better fit, but since you asked specifically for a non-jshell solution..

murtiko
  • 253
  • 1
  • 3
  • 14