Of course! The phrase "Java import python" can mean a few different things. I'll cover the most common interpretations, from the most practical (running Python code from Java) to the more conceptual (using Python-like features in Java).

Let's break it down.
Summary Table
| Method | How it Works | Best For | Pros | Cons |
|---|---|---|---|---|
| ProcessBuilder | Java starts a new, separate Python process. | Running simple Python scripts, quick tasks. | Simple to implement, no extra libraries needed. | Slow (high overhead), no easy data exchange, complex to manage. |
| Jython | Python code runs directly on the Java Virtual Machine (JVM). | Legacy systems, integrating Python libraries into a Java app. | True integration, shared memory, good performance. | Not compatible with standard CPython libraries. |
| GraalVM | A high-performance polyglot VM that runs both Java and Python. | High-performance applications, microservices, modern architectures. | Excellent performance, seamless data exchange, runs standard Python. | Complex setup, newer technology, smaller community than others. |
| JPype | A bridge that creates a Python interpreter inside the JVM. | Scientific computing, data science (NumPy, Pandas). | Access to standard CPython libraries and its ecosystem. | Can be complex to configure, potential for memory leaks. |
| Subprocess | A simpler way to run a Python script from the command line. | Quick, one-off script execution. | Very simple, universal. | Very slow, no data exchange, poor error handling. |
Method 1: Using ProcessBuilder (The "Shell Out" Approach)
This is the most common and straightforward method. Your Java application acts as a manager, starts a new Python process, and passes data to it via command-line arguments or standard input/output.
How it works:
Java uses the ProcessBuilder class to execute the python command from your system's shell, passing your script file and any arguments.
Example:

Python Script (hello.py)
This script will be called by Java.
# hello.py
import sys
# Get the name from command-line arguments
name = sys.argv[1] if len(sys.argv) > 1 else "World"
# Print the output to standard output
print(f"Hello from Python, {name}!")
Java Code (JavaRunner.java)
This Java code will execute the Python script.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaRunner {
public static void main(String[] args) {
try {
// The command to execute
// Assumes 'python' is in your system's PATH
ProcessBuilder pb = new ProcessBuilder("python", "hello.py", "Java User");
// Start the process
Process process = pb.start();
// Read the output from the Python script
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
System.out.println("Output from Python script:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// Check the exit code
int exitCode = process.waitFor();
System.out.println("\nPython script finished with exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
To Run:
- Save
hello.pyandJavaRunner.javain the same directory. - Compile the Java code:
javac JavaRunner.java - Run the Java code:
java JavaRunner
Pros:

- Simple to implement with standard Java libraries.
- You can use any version of Python and any Python library available on your system.
Cons:
- High Overhead: Starting a new process is slow. Not suitable for frequent calls.
- Complex Data Exchange: Passing complex objects (like lists or custom Java objects) is difficult and requires serialization (e.g., to JSON).
- Error Handling: Handling errors from the Python side in Java can be clunky.
Method 2: Using Jython (The "True Integration" Approach)
Jython is an implementation of the Python programming language that runs on the Java Virtual Machine (JVM). This means your Python code becomes a first-class citizen in your Java application.
How it works: You add the Jython library to your Java project. You can then instantiate Python classes, call Python functions, and pass Java objects directly to Python code, and vice-versa.
Example:
Add Jython Dependency (Maven)
Add this to your pom.xml:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.3</version> <!-- Use a recent stable version -->
</dependency>
Python Script (greeter.py)
This is a standard Python script that Jython can interpret.
# greeter.py
def greet(name):
"""A simple Python function that returns a greeting string."""
return f"Greetings from Jython, {name}!"
Java Code (JythonRunner.java)
import org.python.util.PythonInterpreter;
public class JythonRunner {
public static void main(String[] args) {
// Create a new Python interpreter
try (PythonInterpreter py = new PythonInterpreter()) {
// Execute the Python script file
py.execfile("greeter.py");
// Get a Java String object
String javaName = "Java Developer";
// Set a variable in the Python namespace
py.set("name", javaName);
// Execute a Python statement that calls our function
// and stores the result in a Python variable
py.exec("result = greet(name)");
// Get the result from the Python namespace into a Java variable
String result = (String) py.get("result", String.class);
// Print the result
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Pros:
- True Integration: Seamless data exchange between Java and Python.
- Shared Memory: No need for serialization or process spawning.
- Good performance once initialized.
Cons:
- The Big One: Jython only supports Python 2.7. It is not compatible with modern Python 3 or its vast ecosystem of libraries (like NumPy, Pandas, etc.). This makes it unsuitable for most new projects.
Method 3: Using GraalVM (The "Modern High-Performance" Approach)
GraalVM is a high-performance JDK that can run not just Java, but also JavaScript, Python, Ruby, and other languages on the same virtual machine. It's the most modern and powerful solution.
How it works: You compile your Java application and embed the GraalVM runtime, which includes a Python interpreter. You can call Python functions directly from Java.
Example (Conceptual): The setup is more involved, but the result is elegant.
- Install GraalVM and set it as your
JAVA_HOME. - Install the Python language:
gu install python - Use the GraalVM SDK in your Java code.
// Conceptual GraalVM example
import org.graalvm.polyglot.*;
public class GraalVMRunner {
public static void main(String[] args) {
try (Context context = Context.create()) {
// Directly evaluate Python code
Value result = context.eval("python", "greet('GraalVM User')");
System.out.println(result.asString());
}
}
}
Pros:
- Excellent Performance: Near-native speed for both languages.
- Full Python Compatibility: Runs standard CPython 3.
- Seamless Integration: Easy data exchange between languages.
Cons:
- Complex Setup: Requires installing and managing the GraalVM SDK.
- Newer Technology: The community and tooling are still growing compared to more established methods.
Method 4: Using JPype (The "Scientific Computing" Approach)
JPype is a project that aims to provide a seamless bridge between Java and Python. It creates a Python interpreter inside the JVM, allowing for high-performance communication.
How it works: You start the JPype bridge from your Java code, which starts a Python interpreter. You can then pass Java objects to Python and Python objects to Java.
Pros:
- Access to the full power of the CPython ecosystem, especially scientific libraries like NumPy and Pandas, which are critical for data science.
- Good performance for data-intensive tasks.
Cons:
- Configuration can be complex.
- Requires careful management of memory to avoid leaks between the JVM and the CPython runtime.
Method 5: Using Runtime.getRuntime().exec() (The "Quick and Dirty" Approach)
This is an older, simpler version of ProcessBuilder. It's less flexible and harder to use correctly.
// Example of using the older Runtime class
try {
Process process = Runtime.getRuntime().exec("python hello.py Java User");
// ... (same logic as ProcessBuilder to read output)
} catch (IOException e) {
e.printStackTrace();
}
When to use it: Only for very simple, one-off scripts where you don't need to read the output or handle errors gracefully. ProcessBuilder is almost always a better choice.
Conclusion: Which One Should You Choose?
- For a quick, one-off task or a simple script: Use
ProcessBuilder. It's simple and gets the job done. - For a legacy system or a project that must use Python 2: Use Jython.
- For high-performance, modern applications that need to use the standard Python 3 ecosystem (like Pandas, NumPy): Use GraalVM or JPype. GraalVM is generally the more future-proof and performant choice.
- Avoid
Runtime.exec()unless you have a specific reason.
