Programmatically Get Absolute Path of Java Executable in a Running Program

Do you want to get absolute path of the specific Java executable that was used to launch a program, from within that program itself? May be you want to launch another Java program P2 from a program P1 and you want to make sure that P2 is launched using the same version of Java that was used to launch P1?

It is possible. Java runtime makes available a system property  java.home which contains the path to its installation or root directory. Java executable is usually located (tested on Windows and Mac) inside  java.home in a folder named  bin . We can combine these two facts to get absolute path of the Java executable that was originally used to launch a program. Here is a code snippet that does exactly this:

You will need to import in your source code to compile it. After these couples of lines have executed,  javaExe will contain our required path. You can use it for whatever purpose you want. Here is a sample code snippet that uses this Java executable to launch another Java program in a separate JVM.

TestApp2.jar is the filename of executable jar that will be launched.

I had to figure out this method to fulfill exactly this requirement. I was trying to launch a jar from another jar. It was working fine on Windows but wasn’t working on Mac. Turned out, Mac had two versions of Java installed on it. First jar that I was launching by double click was being launched using a newer version of Java. But the second jar that I was launching from within the first jar using ProcessBuilder was being launched using an older version of Java that was configured on the command line.

I have previously shared a slightly different solution to this problem too in the post titled: SOLUTION: No Java runtime present, requesting install – Mac OS X Yosemite

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Responses on this post

  1. Impressive… How do we know the process that is going to start by processBuilder has a different java version ?
    I guess whenever we start a new process inside a process, it has a new instance of JVM with it, which is totally independent of the process which triggered this. There might be the case the difference of versions is due to list of arguments that may be required by different programs when executed within another program. This link gives some overview on that aspect.
    I am eager to know, how can we make sure the same versions are used by p1 and p2

%d bloggers like this: