Execute Java from Python, Syntax and Examples

  • Post author:
  • Post last modified:May 24, 2019
  • Post category:General
  • Reading time:4 mins read

As per most of the surveys, Python is one of the fastest growing programming language. From web-development to complex scientific calculation, Python is being used in almost all fields. Similar to Python, Java is also one of the widely used programming languages. In this article, we will check how to get access to Java libraries from Python programs. There are lots of modules available to execute Java from Python. We will be discussing one of the such easiest module in this article.

Execute Java from Python

Jpype Python Module

Python provides many modules that allows you to interact with native Java libraries. Among them, jpype is one of the easiest and widely used python module.

Jpype is one of the python module that allows you to interact with Java libraries.

As per the documentation, JPype is an effort to allow Python programs full access to Java class libraries. This is achieved not through re-implementing Python, as Jython/JPython has done, but rather through interfacing at the native level in both virtual machines.

Install Jpype Module

You can use pip to install Jpype in your Python distribution.

Below is the pip command:

pip install JPype1

If you are using Anaconda distribution, then this module is already included in the package. You just have to import required methods from it and start using it.

Execute Java from Python – Example

Now let us understand the Jpype with a working example. Below example demonstrate usage of Jpype module.

from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("Calling Java Print from Python using Jpype!")
shutdownJVM()

Note that, you can directly use getDefaultJVMPath() method to get jvm location. Alternatively, you can directly pass jvm location to startJVM() method.

Output:

C:\Users\vithal.sampagar\AppData\Local\ Continuum\anaconda2\python.exe C:/Users/vithal.sampagar/PycharmProjects /AlgosWithPython/test.py 
Calling Java Print from Python using Jpype!

JVM has been shutdown

Foot Note

Please note that,

  • You should have Java installed on the system.
  • You should provide jvm location to script
  • Don’t forget to shutdown jvm after execution

Related Article

Hope this helps 🙂