tags:

views:

121

answers:

4

Is it possible to execute a JAR file on any OS (like Windows, Linux, Mac OS X)? I want to build a simple application that I want to run on Linux, Windows, and Mac OS X. Could the JAR file be run on any OS with java installed?

+5  A: 

The Jar files run on any OS for which a JVM exists.

Snehal
Well, on any O/S for which the required version of the JVM is installed; if you use Java 6 APIs a Java 5 JVM does you no good.
Software Monkey
+5  A: 

Yes, as long as you don't use any native libraries (JNI) this is how java works. It's platform independent.

tangens
And no Java Native Access :-) and keep in mind that the filepath separator is different on each platform.
Pindatjuh
@Pindatjuh: JNA is a layer on top of JNI so the native support limitation is a given; however it has support for multiple O/S's and, as it happens, JNA support the 3 he specifically mentions: `JNA has been built and tested on OSX (ppc, x86, x86_64), linux (x86, amd64), FreeBSD/OpenBSD (x86, amd64), Solaris (x86, amd64, sparc, sparcv9) and Windows (x86, amd64). It has also been built for windows/mobile and Linux/ppc64, although those platforms are not included in the distribution.`
Software Monkey
+2  A: 

Jar files are designed to run on any OS that has a JVM of a compatible version installed. Some jar files, however, may have be compiled from Java code that used OS-specific code (say talking to Windows registries), so testing it on other OS's is wise.

Kathy Van Stone
+3  A: 

As other said, as long as you have Java installed and avoid using native code, you should be good to go. One thing to note is that you can usually run a JAR file just by double clicking it, and it opens like a native executable (on Windows this is how it works by default, on other OSes you can configure this behavior).

Such JAR files are called executable JAR files. If what you want to create is an executable JAR file, then you need to add a manifest file that tells the Java virtual machine (JVM) the name of the main class. Executable JAR files also can be run on the command line by doing:

java -jar myprogram.jar

If your JAR is not an executable JAR, then to run your program you have to add the JAR to your classpath and then execute the main class. To add a JAR to the classpath:

java -classpath path/to/your/program.jar com.mypackage.Main
Cesar
Double-clicking directly on a JAR rarely work, because it means that no arguments are sent to main or to the JVM.
Skeptic
@Skeptic: Define "rarely". In practice I use lots of Java programs an none of them require command line arguments.
Software Monkey