javac [ options ] [ sourcefiles ] [ @argfiles ]Arguments may be in any order.
options- Command-line options.
sourcefiles- One or more source files to be compiled (such as MyClass.java).
@argfiles- One or more files that lists options and source files. The
-Joptions are not allowed in these files.
Thejavac tool reads class and interface definitions, written inthe Java programming language, and compiles them into bytecode classfiles.There are two ways to pass source code file names tojavac:
Source code file names must have
- For a small number of source files, simply list the file names on the command line.
- For a large number of source files, list the file names in a file, separated by blanks or line breaks. Then use the list file name on thejavac command line, preceded by an@ character.
.javasuffixes,class file names must have.classsuffixes, and bothsource and class files must have root names that identify the class. Forexample, a class calledMyClasswould be written in asource file calledMyClass.javaand compiled into abytecode class file calledMyClass.class.Inner class definitionsproduce additional class files. These class files have names combiningthe inner and outer class names, such as
MyClass$MyInnerClass.class.You should arrange source files in a directory tree that reflects theirpackage tree. For example, if you keep all your source files in/workspace, the source code for
com.mysoft.mypack.MyClassshould be in/workspace/com/mysoft/mypack/MyClass.java.By default, the compiler puts each class file in the same directory asits source file. You can specify a separate destination directory with-d (seeOptions, below).
When compiling a source file, the compiler often needs informationabout a type whose definition did not appear in the source filesgiven on the command line. The compiler needs typeinformation for every class or interface used, extended, or implementedin the source file. This includes classes and interfaces not explicitlymentioned in the source file but which provide information throughinheritance.For example, when you subclassjava.applet.Applet, you are alsousingApplet's ancestor classes:java.awt.Panel,java.awt.Container,java.awt.Component, andjava.lang.Object.
When the compiler needs type information, itlooks 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 theCLASSPATH environment variable or by using the-classpathcommand line option. (For details, seeSetting 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; seeCross-Compilation Options below.
A successful type search may produce a class file, a source file, orboth. Here is howjavac handles each situation:
Note: javac can silently compile source files not mentionedon the command line. Use the-verbose option to trace automaticcompilation.
- Search produces a class file but no source file:javac uses the class file.
- Search produces a source file but no class file:javac compiles the source file and uses the resulting class file.
- Search produces both a source file and a class file:javac determines whether the class file is out of date. If the class file is out of date,javac recompiles the source file and uses the updated class file. Otherwise,javac just uses the class file.
javac considers a class file out of date only if it is older than the source file.
The compiler has a set of standard options that are supported on thecurrent development environment and will be supported in future releases.An additional set of non-standard options are specific to the currentvirtual machine and compiler implementations and are subject to changein the future. Non-standard options begin with-X.
- -classpathclasspath
- Set the user class path, overriding the user class path intheCLASSPATH environment variable. If neitherCLASSPATH or-classpath is specified, the userclass path consists of the current directory. SeeSetting the Class Path for more details.
If the-sourcepath option is not specified, the userclass path is searched for both source files and class files.
- -Djava.ext.dirs=directories
- Override the location of installed extensions.
- -Djava.endorsed.dirs=directories
- Override the location of endorsed standards path.
- -ddirectory
- Set the destination directory for class files. The destination directory must already exist; javac will not create the destination directory. If a classis part of a package,javac puts the class file in asubdirectory reflecting the package name, creating directoriesas needed. For example, if you specify-d /home/myclassesand the class is called
com.mypackage.MyClass,then the class file is called/home/myclasses/com/mypackage/MyClass.class.If-d is not specified,javac puts the class filein the same directory as the source file.
Note: The directory specified by-d is not automatically added to your user class path.
- -deprecation
- Show a description of each use or override of a deprecatedmember or class. Without-deprecation,javacshows the names of source files that use or override deprecatedmembers or classes.-deprecation is shorthand for-Xlint:deprecation.
- -encodingencoding
- Set the source file encoding name, such as
EUC-JP and UTF-8.. If-encoding is not specified,the platform default converter is used.- -g
- Generate all debugging information, including local variables.By default, only line number and source file information is generated.
- -g:none
- Do not generate any debugging information.
- -g:{keyword list}
- Generate only some kinds of debugging information, specifiedby a comma separated list of keywords. Valid keywords are:
- source
- Source file debugging information
- lines
- Line number debugging information
- vars
- Local variable debugging information
- -help
- Print a synopsis of standard options.
- -nowarn
- Disable warning messages.This has the same meaning as-Xlint:none.
- -sourcerelease
- Specifies the version of source code accepted. The following values forrelease are allowed:
1.3 the compiler doesnot support assertions, generics, or other language features introduced after JDK 1.3. 1.4 the compiler accepts code containing assertions, which were introduced in JDK 1.4. 1.5 the compiler accepts code containing generics and other language features introduced in JDK 5. The compiler defaults to version 5 behavior if the-source flag is not used. 5 Synonym for 1.5
- -sourcepathsourcepath
- Specify the source code path to search for class orinterface definitions. As with the user class path, source pathentries are separated by colons (:) and can bedirectories, JAR archives, or ZIP archives. If packages areused, the local path name within the directory or archive mustreflect the package name.
Note: Classes found through the classpath are subject toautomatic recompilation if their sources are found.
- -verbose
- Verbose output. This includes information about each classloaded and each source file compiled.
- -X
- Display information about non-standard options and exit.
By default, classes are compiled against the bootstrap and extension classes of the platform thatjavac shipped with. Butjavac also supportscross-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; seeCross-Compilation Example below.
- -targetversion
- Generate class files that will work on VMs with the specified version. The default is to generate class files to be compatible with the JDK 5 VM. When the-source 1.4 or lower option is used, the default target is 1.4. The versions supported byjavac are:
1.1 Generate class files that will run on VMs in JDK 1.1 and later. 1.2 Generate class files that will run on VMs in JDK 1.2 and later, but will not run on 1.1 VMs. 1.3 Generate class files that will run on VMs in JDK 1.3 and later, but will not run on 1.1 or 1.2 VMs. 1.4 Generate class files that will run on VMs in JDK 1.4 and later, but will not run on 1.1, 1.2 or 1.3 VMs. 1.5 Generate class files that are compatible only with JDK 5 VMs. 5 Synonym for 1.5 - -bootclasspathbootclasspath
- Cross-compile against the specified set of boot classes. Aswith the user class path, boot class path entries are separatedby colons (:) and can be directories, JAR archives,or ZIP archives.
- -extdirsdirectories
- Cross-compile against the specified extension directories.Directories is a colon-separated list ofdirectories. Each JAR archive in the specified directories issearched for class files.
- -Xbootclasspath/p:path
- Prepend to the bootstrap class path.
- -Xbootclasspath/a:path
- Append to the bootstrap class path.
- -Xbootclasspath/:path
- Override location of bootstrap class files.
- -Xlint
- Enable all recommended warnings. In this release, all available warnings are recommended.
- -Xlint:none
- Disable all warnings not mandated by the Java Language Specification.
- -Xlint:-xxx
- Disable warningxxx, wherexxx is one of the warning names supported for-Xlint:xxx, below
- -Xlint:unchecked
- Give more detail for unchecked conversion warnings that are mandated by the Java Language Specification.
- -Xlint:path
- Warn about nonexistent path (classpath, sourcepath, etc) directories.
- -Xlint:serial
- Warn about missing
serialVersionUIDdefinitions on serializable classes.- -Xlint:finally
- Warn about
finallyclauses that cannot complete normally.- -Xlint:fallthrough
- Checkswitch blocks for fall-through cases and provide a warning message for any that are found. Fall-through cases are cases in aswitch block, other than the last case in the block, whose code does not include abreak statement, allowing code execution to "fall through" from that case to the next case. For example, the code following thecase 1 label in thisswitch block does not contain abreak statement:
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.switch (x) {case 1: System.out.println("1"); // No break; statement here.case 2: System.out.println("2");}- -Xmaxerrsnumber
- Set the maximum number of errors to print.
- -Xmaxwarnsnumber
- Set the maximum number of warnings to print.
- -Xstdoutfilename
- Send compiler messages to the named file. By default, compiler messages go to
System.err.
- -Joption
- Passoption to thejava launcher called byjavac. For example,-J-Xms48m sets the startupmemory to 48 megabytes.Although it does not begin with-X, it is not a `standardoption' ofjavac.It is a common convention for-J to pass options to the underlying VM executing applications written in Java.
Note: CLASSPATH,-classpath,-bootclasspath,and-extdirs donot specify the classes used to runjavac. Fiddling with the implementation of the compiler in thisway is usually pointless and always risky. If you do need to do this,use the-J option to pass through options to the underlyingjava launcher.
To shorten or simplify the javac command line, you canspecify one or more files that themselves containarguments to thejavaccommand (except-Joptions). This enables you to create javac commands of any length on any operatingsystem.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. 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-Joptions arenot 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 ofthat file into the argument list.
Example - Single Arg File
You could use a single argument file named "argfile" to hold all javac arguments:C:>javac @argfileThis argument file could contain the contents of both files shownin the next example.Example - Two Arg Files
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\classesCreate a file named "
classes" containing:MyClass1.java MyClass2.java MyClass3.javaYou would then run javac with:%javac @options @classesExample - Arg Files with Paths
The argument files can have paths, but any filenames insidethe files are relative to the current working directory (notpath1orpath2):%javac @path1/options @path2/classes
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);
Theargs parameter represents any of the command line arguments that would normally be passed to the javac program and are outlined inthe aboveSynopsis section.
Theout parameter indicates where the compiler's diagnostic output is directed.
The return value is equivalent to the exit value from javac.
Note that allother classes and methods found in a package whose name starts withcom.sun.tools.javac (informally known as sub-packages ofcom.sun.tools.javac) are strictly internal and subject to change at any time.EXAMPLES
Compiling a Simple Program
One source file,Hello.java, defines a class calledgreetings.Hello. Thegreetingsdirectory is thepackage directory both for the source file and the class file and isoff the current directory. This allows us to use the default user classpath. It also makes it unnecessary to specify a separate destinationdirectory with-d.%lsgreetings/%ls greetingsHello.java%cat greetings/Hello.javapackage 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 greetingsHello.class Hello.java%java greetings.Hello World Universe EveryoneHello WorldHello UniverseHello Everyone
This example compiles all the source files in the packagegreetings.%lsgreetings/%ls greetingsAloha.java GutenTag.java Hello.java Hi.java%javac greetings/*.java%ls greetingsAloha.class GutenTag.class Hello.class Hi.classAloha.java GutenTag.java Hello.java Hi.java
Having changed one of the source files in the previous example, werecompile it:Since%pwd/examples%javac greetings/Hi.javagreetings.Hirefers to other classes in thegreetingspackage, the compiler needs to find these otherclasses. The example above works, because our default user class pathhappens to be the directory containing the package directory. Butsuppose we want to recompile this file and not worry about whichdirectory we're in? Then we need to add/examplesto theuser class path. We can do this by settingCLASSPATH, but herewe'll use the-classpath option.If we change%javac -classpath /examples /examples/greetings/Hi.javagreetings.Hiagain, to use a banner utility,that utility also needs to be accessible through the user class path.To execute a class in%javac -classpath /examples:/lib/Banners.jar \ /examples/greetings/Hi.javagreetings, we need access both togreetingsand 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 separatedirectories, especially on large projects. We use-d to indicatethe separate class file destination. Since the source files are not inthe user class path, we use-sourcepath to help the compilerfind them.Note: The compiler compiled%lsclasses/ lib/ src/%ls srcfarewells/%ls src/farewellsBase.java GoodBye.java%ls libBanners.jar%ls classes%javac -sourcepath src -classpath classes:lib/Banners.jar \ src/farewells/GoodBye.java -d classes%ls classesfarewells/%ls classes/farewellsBase.class GoodBye.classsrc/farewells/Base.java,even though we didn't specify it on the command line. To traceautomatic compiles, use the-verbose option.
Here we usejavac to compile code that will run on a 1.4 VM.The-target 1.4 option ensures that the generated class files willbe compatible with 1.4 VMs.By default,javac compiles for JDK 5.%javac -target 1.4 -bootclasspath jdk1.4.2/lib/classes.zip \ -extdirs "" OldCode.javaThe Java 2 SDK'sjavac would also by default compile against its ownbootstrap classes, so we need to telljavac to compile againstJDK 1.4 bootstrap classes instead. We do this with-bootclasspathand-extdirs. Failing to do this might allow compilation against aJava 2 Platform API that would not be present on a 1.4 VM andwould fail at runtime.
![]() |