Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile and build with single command line Java (Linux)

Is there way to set up an alias in such a way so that I could enter the command, followed by the argument in a single line?

For example, instead of

javac Program.java && java Program

I would be able to go

newcommand Program.java //or "newcommand Program", whichever is easier

which would do the same commands as the line above.

like image 408
Nxt3 Avatar asked Sep 13 '14 17:09

Nxt3


3 Answers

Since Java 11 you can use a single command

java example.java

https://openjdk.java.net/jeps/330

Linked: How to compile and run in single command in java

like image 88
Miguel Ángel Júlvez Avatar answered Nov 06 '22 21:11

Miguel Ángel Júlvez


An alias is not made to accept parameters, define a function like this:

jcar() { javac $1.java && java $1 ; }

Then use it:

jcar Program

(jcar was intended as an acronym for java-compile-and-run)

like image 19
enrico.bacis Avatar answered Nov 06 '22 22:11

enrico.bacis


Adding on to enrico.bacis' answer, i personally don't like to have Program.class files cluttering up my workspace if i'm just testing a program, so i'd do

jcar() { javac $1.java && java $1 && rm $1.class}

in addition, i found it helpful to trap ctrl-c so that even if i end the program halfway, it still removes the .class

jcar() {
trap "rm $1.class" SIGINT SIGTERM
javac $1.java
java $1
rm $1.class
}
like image 4
eshanrh Avatar answered Nov 06 '22 22:11

eshanrh