javac [ options ] [ sourcefiles ] [ classes ] [ @argfiles ]
Arguments may be in any order.
options
sourcefiles
classes
@argfiles
-J
options are not allowed in these files.The javac tool reads class and interface definitions, written in the Java programming language, and compiles them into bytecode class files. It can also process annotations in Java source files and classes.
There are two ways to pass source code file names to javac:
Source code file names must have .java
suffixes, class file names must have .class
suffixes, and both source and class files must have root names that identify the class. For example, a class called MyClass
would be written in a source file called MyClass.java
and compiled into a bytecode class file called MyClass.class
.
Inner class definitions produce additional class files. These class files have names combining the inner and outer class names, such as MyClass$MyInnerClass.class
.
You should arrange source files in a directory tree that reflects their package tree. For example, if you keep all your source files in /workspace, the source code for com.mysoft.mypack.MyClass
should be in /workspace/com/mysoft/mypack/MyClass.java.
By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with -d (see Options, below).
The compiler has a set of standard options that are supported on the current development environment and will be supported in future releases. An additional set of non-standard options are specific to the current virtual machine and compiler implementations and are subject to change in the future. Non-standard options begin with -X.
com.mypackage.MyClass
, then the class file is called /home/myclasses/com/mypackage/MyClass.class
.
EUC-JP and UTF-8
. If -encoding is not specified, the platform default converter is used.ext
directory. The directories variable is a colon-separated list of directories. Each JAR archive in the specified directories is searched for class files. All JAR archives found are automatically part of the class path.
com.mypackage.MyClass
, then the source file will be placed in /home/mysrc/com/mypackage/MyClass.java
.By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use -bootclasspath and -extdirs when cross-compiling; see Cross-Compilation Example below.
The default for -target depends on the value of -source:
System.err
.SOURCE
.Enable warning name with the option -Xlint:name, where name is one of the following warning names. Similarly, you can disable warning name with the option -Xlint:-name:
String s = (String)"Hello!"
java.util.Date myDate = new java.util.Date(); int currentDay = myDate.getDay();The method
java.util.Date.getDay
has been deprecated since JDK 1.1.
@deprecated
Javadoc comment, but do not have a @Deprecated
annotation. For example:
/** * @deprecated As of Java SE 7, replaced by {@link #newMethod()} */ public static void deprecatedMethood() { } public static void newMethod() { }
int divideByZero = 42 / 0;
if
statements. For example:
class E { void m() { if (true) ; } }
switch (x) { case 1: System.out.println("1"); // No break statement here. case 2: System.out.println("2"); }If the -Xlint:fallthrough flag were used when compiling this code, the compiler would emit a warning about "possible fall-through into case," along with the line number of the case in question.
finally
clauses that cannot complete normally. For example:
public static int m() { try { throw new NullPointerException(); } catch (NullPointerException e) { System.err.println("Caught NullPointerException."); return 1; } finally { return 0; } }The compiler generates a warning for
finally
block in this example. When this method is called, it returns a value of 0
, not 1
. A finally
block always executes when the try
block exits. In this example, if control is transferred to the catch
, then the method exits. However, the finally
block must be executed, so it is executed, even though control has already been transferred outside the method.
public class ClassWithVarargsMethod { void varargsMethod(String... s) { } }
public class ClassWithOverridingMethod extends ClassWithVarargsMethod { @Override void varargsMethod(String[] s) { } }The compiler generates a warning similar to the following:
ClassWithVarargsMethod.varargsMethod
, the compiler translates the varargs formal parameter String... s
to the formal parameter String[] s
, an array, which matches the formal parameter of the method ClassWithOverridingMethod.varargsMethod
. Consequently, this example compiles.
@SuppressWarnings
annotation. For example:
javac -Xlint:path -classpath /nonexistentpath Example.java
AnnoProc.java
:
import java.util.*; import javax.annotation.processing.*; import javax.lang.model.*; import javax.lang.model.element.*; @SupportedAnnotationTypes("NotAnno") public class AnnoProc extends AbstractProcessor { public boolean process(Set<? extends TypeElement> elems, RoundEnvironment renv) { return true; } public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } }Source file
AnnosWithoutProcessors.java
:
@interface Anno { } @Anno class AnnosWithoutProcessors { }The following commands compile the annotation processor
AnnoProc
, then run this annotation processor against the source file AnnosWithoutProcessors.java
:
% javac AnnoProc.java % javac -cp . -Xlint:processing -processor AnnoProc -proc:only AnnosWithoutProcessors.javaWhen the compiler runs the annotation processor against the source file
AnnosWithoutProcessors.java
, it generates the following warning:
AnnosWithoutProcessors
from Anno
to NotAnno
.
rawtypes
warning:
void countElements(List l) { ... }The following does not generate a
rawtypes
warning:
void countElements(List<?> l) { ... }
List
is a raw type. However, List<?>
is a unbounded wildcard parameterized type. Because List
is a parameterized interface, you should always specify its type argument. In this example, the List
formal argument is specified with a unbounded wildcard (?
) as its formal type parameter, which means that the countElements
method can accept any instantiation of the List
interface.
serialVersionUID
definitions on serializable classes. For example:
public class PersistentTime implements Serializable { private Date time; public PersistentTime() { time = Calendar.getInstance().getTime(); } public Date getTime() { return time; } }The compiler generates the following warning:
serialVersionUID
, then the serialization runtime will calculate a default serialVersionUID
value for that class based on various aspects of the class, as described in the Java Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID
values because the default process of computing serialVersionUID
vales is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions
during deserialization. Therefore, to guarantee a consistent serialVersionUID
value across different Java compiler implementations, a serializable class must declare an explicit serialVersionUID
value.
class XLintStatic { static void m1() { } void m2() { this.m1(); } }The compiler generates the following warning:
warning: [static] static method should be qualified by type name, XLintStatic, instead of by an expressionTo resolve this issue, you can call the static method
m1
as follows:
XLintStatic.m1();Alternatively, you can remove the
static
keyword from the declaration of the method m1
.
try
blocks, including try-with-resources statements. For example, a warning is generated for the following statement because the resource ac
declared in the try
statement is not used:
try ( AutoCloseable ac = getResource() ) { // do nothing }
List l = new ArrayList<Number>(); List<String> ls = l; // unchecked warningDuring type erasure, the types
ArrayList<Number>
and List<String>
become ArrayList
and List
, respectively.
ls
has the parameterized type List<String>
. When the List
referenced by l
is assigned to ls
, the compiler generates an unchecked warning; the compiler is unable to determine at compile time, and moreover knows that the JVM will not be able to determine at runtime, if l
refers to a List<String>
type; it does not. Consequently, heap pollution occurs.
List
object l
, whose static type is List<Number>
, is assigned to another List
object, ls
, that has a different static type, List<String>
. However, the compiler still allows this assignment. It must allow this assignment to preserve backwards compatibility with versions of Java SE that do not support generics. Because of type erasure, List<Number>
and List<String>
both become List
. Consequently, the compiler allows the assignment of the object l
, which has a raw type of List
, to the object ls
.
public class ArrayBuilder { public static <T> void addToList (List<T> listArg, T... elements) { for (T x : elements) { listArg.add(x); } } }The compiler generates the following warning for the definition of the method
ArrayBuilder.addToList
:
warning: [varargs] Possible heap pollution from parameterized vararg type TWhen the compiler encounters a varargs method, it translates the varargs formal parameter into an array. However, the Java programming language does not permit the creation of arrays of parameterized types. In the method
ArrayBuilder.addToList
, the compiler translates the varargs formal parameter T... elements
to the formal parameter T[] elements
, an array. However, because of type erasure, the compiler converts the varargs formal parameter to Object[] elements
. Consequently, there is a possibility of heap pollution.
To shorten or simplify the javac command line, you can specify one or more files that themselves contain arguments to the javac
command (except -J
options). This enables you to create javac commands of any length on any operating system.
An argument file can include javac options and source filenames in any combination. The arguments within a file can be space-separated or newline-separated. If a filename contains embedded spaces, put the whole filename in double quotes.
Filenames within an argument file are relative to the current directory, not the location of the argument file. Wildcards (*) are not allowed in these lists (such as for specifying *.java
). Use of the '@' character to recursively interpret files is not supported. The -J
options are not supported because they are passed to the launcher, which does not support argument files.
When executing javac, pass in the path and name of each argument file with the '@' leading character. When javac encounters an argument beginning with the character `@', it expands the contents of that file into the argument list.
You could use a single argument file named "argfile
" to hold all javac arguments:
% javac @argfile
This argument file could contain the contents of both files shown in the next example.
You can create two argument files -- one for the javac options and the other for the source filenames: (Notice the following lists have no line-continuation characters.)
Create a file named "options
" containing:
-d classes -g -sourcepath /java/pubs/ws/1.3/src/share/classes
Create a file named "classes
" containing:
MyClass1.java MyClass2.java MyClass3.java
You would then run javac with:
% javac @options @classes
The argument files can have paths, but any filenames inside the files are relative to the current working directory (not path1
or path2
):
% javac @path1/options @path2/classes
javac provides direct support for annotation processing, superseding the need for the separate annotation processing tool, apt.
The API for annotation processors is defined in the javax.annotation.processing
and javax.lang.model
packages and subpackages.
Unless annotation processing is disabled with the -proc:none option, the compiler searches for any annotation processors that are available. The search path can be specified with the -processorpath option; if it is not given, the user class path is used. Processors are located by means of service provider-configuration files named META-INF/services/javax.annotation.processing.Processor
on the search path. Such files should contain the names of any annotation processors to be used, listed one per line. Alternatively, processors can be specified explicitly, using the -processor option.
After scanning the source files and classes on the command line to determine what annotations are present, the compiler queries the processors to determine what annotations they process. When a match is found, the processor will be invoked. A processor may "claim" the annotations it processes, in which case no further attempt is made to find any processors for those annotations. Once all annotations have been claimed, the compiler does not look for additional processors.
If any processors generate any new source files, another round of annotation processing will occur: any newly generated source files will be scanned, and the annotations processed as before. Any processors invoked on previous rounds will also be invoked on all subsequent rounds. This continues until no new source files are generated.
After a round occurs where no new source files are generated, the annotation processors will be invoked one last time, to give them a chance to complete any work they may need to do. Finally, unless the -proc:only option is used, the compiler will compile the original and all the generated source files.
To compile a set of source files, the compiler may need to implicitly load additional source files. (See Searching For Types). Such files are currently not subject to annotation processing. By default, the compiler will give a warning if annotation processing has occurred and any implicitly loaded source files are compiled. See the -implicit option for ways to suppress the warning.
When compiling a source file, the compiler often needs information about a type whose definition did not appear in the source files given on the command line. The compiler needs type information for every class or interface used, extended, or implemented in the source file. This includes classes and interfaces not explicitly mentioned in the source file but which provide information through inheritance.
For example, when you subclass java.applet.Applet, you are also using Applet's ancestor classes: java.awt.Panel, java.awt.Container, java.awt.Component, and java.lang.Object.
When the compiler needs type information, it looks for a source file or class file which defines the type. The compiler searches for class files first in the bootstrap and extension classes, then in the user class path (which by default is the current directory). The user class path is defined by setting the CLASSPATH environment variable or by using the -classpath command line option. (For details, see Setting the Class Path).
If you set the -sourcepath option, the compiler searches the indicated path for source files; otherwise the compiler searches the user class path for both class files and source files.
You can specify different bootstrap or extension classes with the -bootclasspath and -extdirs options; see Cross-Compilation Options below.
A successful type search may produce a class file, a source file, or both. If both are found, you can use the -Xprefer option to instruct the compiler which to use. If newer is given, the compiler will use the newer of the two files. If source is given, it will use the source file. The default is newer.
If a type search finds a source file for a required type, either by itself, or as a result of the setting for -Xprefer, the compiler will read the source file to get the information it needs. In addition, it will by default compile the source file as well. You can use the -implicit option to specify the behavior. If none is given, no class files will be generated for the source file. If class is given, class files will be generated for the source file.
The compiler may not discover the need for some type information until after annotation processing is complete. If the type information is found in a source file and no -implicit option is given, the compiler will give a warning that the file is being compiled without being subject to annotation processing. To disable the warning, either specify the file on the command line (so that it will be subject to annotation processing) or use the -implicit option to specify whether or not class files should be generated for such source files.
javac supports the new Java Compiler API defined by the classes and interfaces in the javax.tools
package.
To perform a compilation using arguments as you would give on the command line, you can use the following:
JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); int rc = javac.run(null, null, null, args);
This will write any diagnostics to the standard output stream, and return the exit code that javac would give when invoked from the command line.
You can use other methods on the javax.tools.JavaCompiler
interface to handle diagnostics, control where files are read from and written to, and so on.
Note: This API is retained for backwards compatibility only; all new code should use the Java Compiler API, described above.
The com.sun.tools.javac.Main
class provides two static methods to invoke the compiler from a program:
public static int compile(String[] args); public static int compile(String[] args, PrintWriter out);
The args
parameter represents any of the command line arguments that would normally be passed to the javac program and are outlined in the above Synopsis section.
The out
parameter indicates where the compiler's diagnostic output is directed.
The return value is equivalent to the exit value from javac.
Note that all other classes and methods found in a package whose name starts with com.sun.tools.javac
(informally known as sub-packages of com.sun.tools.javac
) are strictly internal and subject to change at any time.
One source file, Hello.java
, defines a class called greetings.Hello. The greetings
directory is the package directory both for the source file and the class file and is off the current directory. This allows us to use the default user class path. It also makes it unnecessary to specify a separate destination directory with -d.
% ls greetings/ % ls greetings Hello.java % cat greetings/Hello.java package greetings; public class Hello { public static void main(String[] args) { for (int i=0; i < args.length; i++) { System.out.println("Hello " + args[i]); } } } % javac greetings/Hello.java % ls greetings Hello.class Hello.java % java greetings.Hello World Universe Everyone Hello World Hello Universe Hello Everyone
This example compiles all the source files in the package greetings
.
% ls greetings/ % ls greetings Aloha.java GutenTag.java Hello.java Hi.java % javac greetings/*.java % ls greetings Aloha.class GutenTag.class Hello.class Hi.class Aloha.java GutenTag.java Hello.java Hi.java
Having changed one of the source files in the previous example, we recompile it:
% pwd /examples % javac greetings/Hi.java
Since greetings.Hi
refers to other classes in the greetings
package, the compiler needs to find these other classes. The example above works, because our default user class path happens to be the directory containing the package directory. But suppose we want to recompile this file and not worry about which directory we're in? Then we need to add /examples
to the user class path. We can do this by setting CLASSPATH, but here we'll use the -classpath option.
% javac -classpath /examples /examples/greetings/Hi.java
If we change greetings.Hi
again, to use a banner utility, that utility also needs to be accessible through the user class path.
% javac -classpath /examples:/lib/Banners.jar \ /examples/greetings/Hi.java
To execute a class in greetings
, we need access both to greetings
and to the classes it uses.
% java -classpath /examples:/lib/Banners.jar greetings.Hi
It often makes sense to keep source files and class files in separate directories, especially on large projects. We use -d to indicate the separate class file destination. Since the source files are not in the user class path, we use -sourcepath to help the compiler find them.
% ls classes/ lib/ src/ % ls src farewells/ % ls src/farewells Base.java GoodBye.java % ls lib Banners.jar % ls classes % javac -sourcepath src -classpath classes:lib/Banners.jar \ src/farewells/GoodBye.java -d classes % ls classes farewells/ % ls classes/farewells Base.class GoodBye.class
Note: The compiler compiled src/farewells/Base.java
, even though we didn't specify it on the command line. To trace automatic compiles, use the -verbose option.
The following example uses javac to compile code that will run on a 1.6 VM.
% javac -source 1.6 -target 1.6 -bootclasspath jdk1.6.0/lib/rt.jar \ -extdirs "" OldCode.java
The -source 1.6
option specifies that version 1.6 (or 6) of the Java programming language be used to compile OldCode.java
. The option -target 1.6 option ensures that the generated class files will be compatible with 1.6 VMs. Note that in most cases, the value of the -target option is the value of the -source option; in this example, you can omit the -target option.
You must specify the -bootclasspath option to specify the correct version of the bootstrap classes (the rt.jar
library). If not, the compiler generates a warning:
% javac -source 1.6 OldCode.java warning: [options] bootstrap class path not set in conjunction with -source 1.6
If you do not specify the correct version of bootstrap classes, the compiler will use the old language rules (in this example, it will use version 1.6 of the Java programming language) combined with the new bootstrap classes, which can result in class files that do not work on the older platform (in this case, Java SE 6) because reference to non-existent methods can get included.