7

Java program needs to be packaged to JAR file so it can be executed using java -jar command. So why don't I have to execute javac with java -jar javac command? How did Sun/Oracle make java program into executable binary file?

I know there are tools that can convert jar file to windows executable file. But I want my jars to be executable in Linux/OS X without the help of bash script.

---------- UPDATE

I found this link really helpful: https://github.com/maynooth/CS210/wiki/Convert-Java-Executable-to-Linux-Executable

Neo
  • 2,106
  • 5
  • 30
  • 58

1 Answers1

4

If javac was written in Java, why I can execute javac as if it is a none-java program?

The answer to your question has already been given by Jon Skeet for the question Why Java compiler as distributed as executable and not as JVM bytecode?

Quoting his answer here below

javac.exe (on my installation, JDK 1.8 on Windows x64) is about 15K in size. This isn't the full compiler. The compiler itself really is written in Java, and javac.exe is just a launcher, effectively. This is true of many of the tools that come with Java - it would be a pain to have to run something like:

java -cp path/to/javac.jar java.tools.Javac -cp path/to/your/libraries Foo.java

A simple way to understand the whole thing is imagining JRE(Java runtime environment) acting like an intermediate layer between your program and the OS. JRE accepts the bytecode and runs your java program.The javac (java compiler ) converts your java source code to platform neutral byte code(exceptions are there). I am not sure if java,javac,jre is written in java or not. But if they are,then they have to linked/loaded in a different way in different OS(platforms).

Now coming to how to run jar in windows and linux

Normally java code is converted to jar file. Then there will be two files(mostly along with jar file) to start the jar file , one for windows and one for linux

For example Apache tomcat has files (in same location)

startup.bat ==> to start program in windows.
startup.sh  ==> to start program in linux.

Alternately you could convert jar to exe for windows. For linux the link you specified is enough. The script is interpreted by command interpreter in linux and your jar file will be executed.

This link specifies different ways of executing a shell script in linux. http://www.thegeekstuff.com/2010/07/execute-shell-script/

This link has code to run jar as bat Run .jar from batch-file

To sum it up , your jar file can be platform independent but they way to start the jar file will differ for different platforms.

Community
  • 1
  • 1
Raj
  • 1,907
  • 16
  • 38