Back to Python
2025-12-275 min read

Java Compiler (Python Programming)

Learn Java Compiler (Python Programming) step by step with clear examples and exercises.

Why This Matters

Java is a popular and widely used programming language, but what if you want to write Java code using Python? In this lesson, we'll discuss how to use a Java compiler within Python, making it possible to compile and run Java code from Python scripts.

Why This Matters

There are several reasons why you might want to use a Java compiler within Python:

  1. Convenience: You can write, compile, and run Java code all from one Python script, eliminating the need to switch between different IDEs or command lines.
  2. Automation: By automating the compilation process, you can create scripts that generate multiple Java files based on templates or data input, making it easier to manage large projects.
  3. Integration: If you're working on a project that combines Python and Java components, using a Java compiler within Python allows for seamless integration between the two languages.
  4. Debugging: By running your Java code within a Python script, you can use Python's powerful debugging tools to help find and fix issues in your Java code more easily.

Prerequisites

To follow along with this lesson, you will need:

  1. A basic understanding of both Python and Java programming languages.
  2. Python 3 installed on your system.
  3. The subprocess module for Python, which allows you to run external commands from within a Python script.
  4. A Java Development Kit (JDK) installed on your system.

Core Concept

To use a Java compiler within Python, we'll use the subprocess module to execute the javac command-line tool that comes with the JDK. Here's an example of how you can compile and run a simple Java program from a Python script:

import subprocess

Define the Java source code

java_source = """

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

}

}

"""

Compile the Java source code

compile_command = "javac -cp . HelloWorld.java"

subprocess.run(compile_command, shell=True, stdout=subprocess.PIPE)

Run the compiled Java class

run_command = "java HelloWorld"

output = subprocess.run(run_command, shell=True, stdout=subprocess.PIPE).stdout

print("Output:", output.decode())


Let's break this down:

1. We start by importing the `subprocess` module, which allows us to run external commands from within our Python script.
2. Next, we define a string containing the Java source code for a simple "Hello, World!" program.
3. To compile the Java source code, we create a command string that includes the `javac` command along with the class name and source file. We then use the `subprocess.run()` function to execute this command, capturing the output in case there are any errors during compilation.
4. Once the Java code is compiled, we can run it by creating another command string that includes the name of the compiled class (without the .class extension). We again use `subprocess.run()` to execute this command and capture the output.
5. Finally, we print the output from the Java program.

Worked Example

Let's work through an example where we write a Python script that takes a list of Java source files as input, compiles them all, and then runs the compiled classes. Save this code in a file called java_compiler.py:

import sys
import subprocess

def compile_and_run(source_files):
for source in source_files:

Compile the Java source code

compile_command = "javac -cp . " + source

subprocess.run(compile_command, shell=True, stdout=subprocess.PIPE)

Run all compiled classes

for source in source_files:

class_name = source.split(".")[-1].replace(".java", "")

run_command = "java " + class_name

output = subprocess.run(run_command, shell=True, stdout=subprocess.PIPE).stdout

print("Output for {}:".format(class_name))

print(" ", output.decode())

if __name__ == "__main__":

source_files = sys.argv[1:]

if not source_files:

print("Usage: python java_compiler.py [ ...]")

sys.exit(1)

compile_and_run(source_files)


Now, create a directory called `java_examples` and place the following Java source files inside:

- `HelloWorld.java` (the same code as in the previous example)
- `Sum.java`:

public class Sum {

public static void main(String[] args) {

int a = 5;

int b = 10;

System.out.println("The sum is: " + (a + b));

}

}


To compile and run these Java examples using the Python script, open a terminal or command prompt, navigate to the directory containing `java_compiler.py`, and execute the following command:

python java_compiler.py HelloWorld.java Sum.java


This will compile both Java files and run each of the compiled classes, producing the following output:

Output for HelloWorld:

Hello, World!

Output for Sum:

The sum is: 15

Common Mistakes

  1. Forgetting to import the subprocess module: Make sure you have import subprocess at the beginning of your Python script.
  2. Incorrect command syntax: Be sure to use proper command syntax when calling javac and java. For example, if your Java source file is in a package, you'll need to include the package name when compiling and running the class.
  3. Not capturing output: If there are errors during compilation or execution of the Java code, make sure to capture the output using stdout=subprocess.PIPE so that it can be printed or handled appropriately.
  4. Misunderstanding error messages: When encountering errors, carefully read and understand the error messages. They usually provide valuable clues about what went wrong and how to fix it.

Practice Questions

  1. Modify the java_compiler.py script to accept a list of Java files as command-line arguments and compile/run them all in one go (as shown in the worked example).
  2. Create a new Java class called AreaCircle that calculates the area of a circle given its radius. Write a Python script that compiles this Java class, creates an instance of it, sets the radius to 5, and prints the calculated area.
  3. Modify the java_compiler.py script to accept a directory containing multiple Java files as input, compile/run all the classes in that directory, and print the output for each class separately.

FAQ

  1. Why do I need to include . in the compile command?: The . represents the current working directory, which is where the compiled class files will be placed. Including it ensures that the compiled classes can find any required packages or resources within the same directory as the source code.
  2. Can I use a different Java compiler (e.g., Eclipse JDT) instead of javac?: Yes, you can use other Java compilers by specifying their paths in the compile command. However, this may require additional configuration and dependencies.
  3. How can I handle errors during compilation or execution using Python's subprocess module?: You can capture the output using stdout=subprocess.PIPE and check for error codes returned by the subprocess.run() function to determine if there were any issues during execution.
  4. Can I use a Java compiler within Python for more complex projects, like Android development or web applications?: Yes, but it may require additional setup and configuration depending on the specific project requirements. For example, you might need to set up classpaths, include external libraries, or create custom build scripts.
Java Compiler (Python Programming) | Python | XQA Learn