A Java compiler is a compiler for the Java programming language.

Some Java compilers output optimized machine code for a particular hardware/operating system combination, called a domain specific computer system. An example would be the now discontinued GNU Compiler for Java.

The most common form of output from a Java compiler is Java class files containing cross-platform intermediate representation (IR), called Java bytecode.

The Java virtual machine (JVM) loads the class files and either interprets the bytecode or just-in-time compiles it to machine code and then possibly optimizes it using dynamic compilation.

A standard on how to interact with Java compilers was specified in JSR 199.

It is provided by module <code>jdk.compiler</code>, and requires the full Java Development Kit (as opposed to just the Java Runtime Environment), and reside in the <code>javax.tools.*</code> namespace.

Example

<syntaxhighlight lang="java">

package org.wikipedia.examples;

import java.io.IOException;

import java.io.File;

import javax.tools.JavaCompiler;

import javax.tools.ToolProvider;

public class Example {

private final String TEST_FILE_NAME = "Test.java";

public static void main(String[] args) throws IOException {

File sourceFile = new File(TEST_FILE_NAME);

if (!sourceFile.exists()) {

throw new IllegalArgumentException(String.format("File path %s does not exist!", TIME_FILE_NAME));

}

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

if (compiler == null) {

throw new RuntimeException("Compiler not available. Are you running on a JRE instead of a JDK?");

}

int result = compiler.run(null, null, null, sourceFile);

System.out.printf("Compilation result: %s%n", result == 0 ? "Success" : "Failure");

}

}

</syntaxhighlight>

See also

  • List of Java Compilers
  • javac, the standard Java compiler in Oracle's JDK
  • Roslyn (compiler), compiler for C# also invokable programmatically

References

  • Sun's OpenJDK javac page
  • Stephan Diehl, "A Formal Introduction to the Compilation of Java", Software - Practice and Experience, Vol. 28(3), pages 297-327, March 1998.