JAVAC(1)
β¨ javac(1) β JDK Commands, bestie edition β¨
okay so this is the manual page for javac(1), and itβs literally the compiler for Java declarations. Weβre gonna read the source, compile the class files, and keep every single detail intact. No cap. π
πΈ NAME πΈ
javac β read Java declarations and compile them into class files.
π¦ SYNOPSIS π¦
javac [options] [sourcefiles-or-classnames]
optionsβ Command-line options.sourcefiles-or-classnamesβ Source files to be compiled (for example,Shape.java) or the names of previously compiled classes to be processed for annotations (for example,geometry.MyShape).
π DESCRIPTION π
The way that javac works is: it reads source files containing module, package, and type declarations written in the Java programming language, then compiles them into class files that run on the Java Virtual Machine. Iconic behavior, honestly.
javac can also process annotations in Java source files and classes. Multi-talented.
Source files must have a file name extension of .java. Class files have a file name extension of .class. Both source and class files normally have file names that identify the contents. For example, a class called Shape would be declared in a source file called Shape.java, and compiled into a class file called Shape.class. Slay naming conventions.
There are two ways to specify source files to javac:
- For a small number of source files, you can list their file names on the command line.
- For a large number of source files, you can use the
@filenameoption on the command line to specify an argument file that lists their file names. See Standard Options for a description of the option and Command-Line Argument Files for a description ofjavacargument files.
The order of source files specified on the command line or in an argument file is not important. javac will compile the files together, as a group, and will automatically resolve any dependencies between the declarations in the various source files. Group project but the compiler actually carries.
javac expects that source files are arranged in one or more directory hierarchies on the file system, described in Arrangement of Source Code.
To compile a source file, javac needs to find the declaration of every class or interface that is used, extended, or implemented by the code in the source file. This lets javac check that the code has the right to access those classes and interfaces. Rather than specifying the source files of those classes and interfaces explicitly, you can use command-line options to tell javac where to search for their source files. If you have compiled those source files previously, you can use options to tell javac where to search for the corresponding class files. The options, which all have names ending in "path", are described in Standard Options, and further described in Configuring a Compilation and Searching for Module, Package and Type Declarations.
By default, javac compiles each source file to a class file in the same directory as the source file. However, it is recommended to specify a separate destination directory with the -d option. Do that. Your future self will thank you.
Command-line options and environment variables also control how javac performs various tasks:
- Compiling code to run on earlier releases of the JDK.
- Compiling code to run under a debugger.
- Checking for stylistic issues in Java source code.
- Checking for problems in javadoc comments (
/** ... */). - Processing annotations in source files and class files.
- Upgrading and patching modules in the compile-time environment.
javac supports Compiling for Earlier Releases Of The Platform and can also be invoked from Java code using one of a number of APIs. versatile queen π
π OPTIONS π
javac provides standard options, and extra options that are either non-standard or are for advanced use.
Some options take one or more arguments. If an argument contains spaces or other whitespace characters, the value should be quoted according to the conventions of the environment being used to invoke javac. If the option begins with a single dash (-) the argument should either directly follow the option name, or should be separated with a colon (:) or whitespace, depending on the option. If the option begins with a double dash (--), the argument may be separated either by whitespace or by an equals (=) character with no additional whitespace. For example,
-Aname="J. Duke"
-proc:only
-d myDirectory
--module-version 3
--module-version=3
In the following lists of options, an argument of path represents a search path, composed of a list of file system locations separated by the platform path separator character, (semicolon ; on Windows, or colon : on other systems.) Depending on the option, the file system locations may be directories, JAR files or JMOD files. iykyk path separator vibes.
π Standard Options π
@filenameβ Reads options and file names from a file. To shorten or simplify thejavaccommand, you can specify one or more files that contain arguments to thejavaccommand (except-Joptions). This lets you createjavaccommands of any length on any operating system. See Command-Line Argument Files.-Akey[=value]β Specifies options to pass to annotation processors. These options are not interpreted byjavacdirectly, but are made available for use by individual processors. Thekeyvalue should be one or more identifiers separated by a dot (.).--add-modules module,moduleβ Specifies root modules to resolve in addition to the initial modules, or all modules on the module path ifmoduleisALL-MODULE-PATH.--boot-class-path pathor-bootclasspath pathβ Overrides the location of the bootstrap class files. Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details. For JDK 9 or later, see--system.--class-path path,-classpath path, or-cp pathβ Specifies where to find user class files and annotation processors. This class path overrides the user class path in theCLASSPATHenvironment variable.- If
--class-path,-classpath, or-cpare not specified, then the user class path is the value of theCLASSPATHenvironment variable, if that is set, or else the current directory. - If not compiling code for modules, if the
--source-pathor-sourcepathoption is not specified, then the user class path is also searched for source files. - If the
-processorpathoption is not specified, then the class path is also searched for annotation processors.
- If
-d directoryβ Sets the destination directory (or class output directory) for class files. If a class is part of a package, thenjavacputs the class file in a subdirectory that reflects the module name (if appropriate) and package name. The directory, and any necessary subdirectories, will be created if they do not already exist. If the-doption is not specified, thenjavacputs each class file in the same directory as the source file from which it was generated. Except when compiling code for multiple modules, the contents of the class output directory will be organized in a package hierarchy. When compiling code for multiple modules, the contents of the output directory will be organized in a module hierarchy, with the contents of each module in a separate subdirectory, each organized as a package hierarchy. Note: When compiling code for one or more modules, the class output directory will automatically be checked when searching for previously compiled classes. When not compiling for modules, for backwards compatibility, the directory is not automatically checked for previously compiled classes, and so it is recommended to specify the class output directory as one of the locations on the user class path, using the--class-pathoption or one of its alternate forms.-deprecationβ Shows a description of each use or override of a deprecated member or class. Without the-deprecationoption,javacshows a summary of the source files that use or override deprecated members or classes. The-deprecationoption is shorthand for-Xlint:deprecation.--enable-previewβ Enables preview language features. Used in conjunction with either-sourceor--release.-encoding encodingβ Specifies character encoding used by source files, such asEUC-JPandUTF-8. If the-encodingoption is not specified, then the platform default converter is used.-endorseddirs directoriesβ Overrides the location of the endorsed standards path. Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details.-extdirs directoriesβ Overrides the location of the installed extensions.directoriesis a list of directories, separated by the platform path separator (;on Windows, and:otherwise). Each JAR file in the specified directories is searched for class files. All JAR files found become part of the class path. If you are compiling for a release of the platform that supports the Extension Mechanism, then this option specifies the directories that contain the extension classes. See[Compiling for Other Releases of the Platform]. Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details.-gβ Generates all debugging information, including local variables. By default, only line number and source file information is generated.-g:[lines, vars, source]β Generates only the kinds of debugging information specified by the comma-separated list of keywords. Valid keywords are:linesβ Line number debugging information.varsβ Local variable debugging information.sourceβ Source file debugging information.
-g:noneβ Does not generate debugging information.-h directoryβ Specifies where to place generated native header files. When you specify this option, a native header file is generated for each class that contains native methods or that has one or more constants annotated with thejava.lang.annotation.Nativeannotation. If the class is part of a package, then the compiler puts the native header file in a subdirectory that reflects the module name (if appropriate) and package name. The directory, and any necessary subdirectories, will be created if they do not already exist. Generated headers, organized and cute. π--help,-helpor-?β okay so this one prints a synopsis of the standard options. π--help-extraor-Xβ prints a synopsis of the set of extra options. β¨--help-lintβ prints the supported keys for the-Xlintoption. π-implicit:[none, class]β tells the compiler whether or not to generate class files for implicitly referenced files:-implicit:classβ automatically generates class files. π«Ά-implicit:noneβ suppresses class file generation. If this option is not specified, then the default automatically generates class files. In this case, the compiler issues a warning if any class files are generated when also doing annotation processing. The warning is not issued when the-implicitoption is explicitly set. See Searching for Module, Package and Type Declarations. πΈ
-Joptionβ passes option to the runtime system, where option is one of the Java options described on thejavacommand. For example,-J-Xms48msets the startup memory to 48 MB. β οΈ Note: TheCLASSPATHenvironment variable,-classpathoption,-bootclasspathoption, and-extdirsoption do not specify the classes used to runjavac. Trying to customize the compiler implementation with these options and variables is risky and often does not accomplish what you want. If you must customize the compiler implementation, then use the-Joption to pass options through to the underlying Java launcher. π--limit-modules module,module*β limits the universe of observable modules. π¦--module module-name (,module-name)*or-m module-name (,module-name)*β compiles those source files in the named modules that are newer than the corresponding files in the output directory. π--module-path pathor-p pathβ specifies where to find application modules. π--module-source-path module-source-pathβ specifies where to find source files when compiling code in multiple modules. See The Module Source Path Option. π§--module-version versionβ specifies the version of modules that are being compiled. β-nowarnβ generate only mandatory warnings. π-parametersβ generates metadata for reflection on method parameters. Stores formal parameter names of constructors and methods in the generated class file so that the methodjava.lang.reflect.Executable.getParametersfrom the Reflection API can retrieve them. π₯-proc:[none, only, full]β controls whether annotation processing and compilation are done:-proc:nonemeans that compilation takes place without annotation processing. π-proc:onlymeans that only annotation processing is done, without any subsequent compilation. β¨-proc:fullmeans annotation processing and compilation are done. If this option is not used, annotation processing and compilation are done if at least one other option is used to explicitly configure annotation processing. π
-processor class1[,class2,class3...]β names of the annotation processors to run. This bypasses the default discovery process. π«Ά--processor-module-path pathβ specifies the module path used for finding annotation processors. πΈ--processor-path pathor-processorpath pathβ specifies where to find annotation processors. If this option is not used, then the class path is searched for processors. π¦-profile profileβ checks that the API used is available in the specified profile. This option is deprecated and may be removed in a future release. β οΈ Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details. π--release releaseβ compiles source code according to the rules of the Java programming language for the specified Java SE release, generating class files which target that release. Source code is compiled against the combined Java SE and JDK API for the specified release. The supported values of release are the current Java SE release and a limited number of previous releases, detailed in the command-line help. For the current release, the Java SE API consists of thejava.*,javax.*, andorg.*packages that are exported by the Java SE modules in the release; the JDK API consists of thecom.*andjdk.*packages that are exported by the JDK modules in the release, plus thejavax.*packages that are exported by standard, but non-Java SE, modules in the release. For previous releases, the Java SE API and the JDK API are as defined in that release. β οΈ Note: When using--release, you cannot also use the--source/-sourceor--target/-targetoptions. β οΈ Note: When using--releaseto specify a release that supports the Java Platform Module System, the--add-exportsoption cannot be used to enlarge the set of packages exported by the Java SE, JDK, and standard modules in the specified release. π-s directoryβ specifies the directory used to place the generated source files. If a class is part of a package, then the compiler puts the source file in a subdirectory that reflects the module name (if appropriate) and package name. The directory, and any necessary subdirectories, will be created if they do not already exist. Except when compiling code for multiple modules, the contents of the source output directory will be organized in a package hierarchy. When compiling code for multiple modules, the contents of the source output directory will be organized in a module hierarchy, with the contents of each module in a separate subdirectory, each organized as a package hierarchy. π--source releaseor-source releaseβ compiles source code according to the rules of the Java programming language for the specified Java SE release. The supported values of release are the current Java SE release and a limited number of previous releases, detailed in the command-line help. If the option is not specified, the default is to compile source code according to the rules of the Java programming language for the current Java SE release. β--source-path pathor-sourcepath pathβ specifies where to find source files. Except when compiling multiple modules together, this is the source code path used to search for class or interface definitions. β οΈ Note: Classes found through the class path might be recompiled when their source files are also found. See Searching for Module, Package and Type Declarations. π§--system jdk | noneβ overrides the location of system modules. π--target releaseor-target releaseβ generates class files suitable for the specified Java SE release. The supported values of release are the current Java SE release and a limited number of previous releases, detailed in the command-line help. β οΈ Note: The target release must be equal to or higher than the source release. (See--source.) π₯--upgrade-module-path pathβ overrides the location of upgradeable modules. π¦-verboseβ outputs messages about what the compiler is doing. Messages include information about each class loaded and each source file compiled. π--versionor-versionβ prints version information. π-Werrorβ terminates compilation when warnings occur. π
π Extra Options β¨
--add-exports module/package=other-module(,other-module)*β specifies a package to be considered as exported from its defining module to additional modules or to all unnamed modules when the value of other-module isALL-UNNAMED. πΈ--add-reads module=other-module(,other-module)*β specifies additional modules to be considered as required by a given module. π«Ά--default-module-for-created-files module-nameβ specifies the fallback target module for files created by annotation processors, if none is specified or inferred. π§--disable-line-doc-commentsβ disables support for documentation comments with lines beginning///. π-Djava.endorsed.dirs=dirsβ overrides the location of the endorsed standards path. β οΈ Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details. π-Djava.ext.dirs=dirsβ overrides the location of installed extensions. β οΈ Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details. π--patch-module module=pathβ overrides or augments a module with classes and resources in JAR files or directories. π-Xbootclasspath:pathβ overrides the location of the bootstrap class files. β οΈ Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details. π-Xbootclasspath/a:pathβ adds a suffix to the bootstrap class path. β οΈ Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details. π-Xbootclasspath/p:pathβ adds a prefix to the bootstrap class path. β οΈ Note: This can only be used when compiling for releases prior to JDK 9. As applicable, see the descriptions in--release,-source, or-targetfor details. π-Xdiags:[compact, verbose]β selects a diagnostic mode. π¦-Xdoclintβ enables recommended checks for problems in documentation comments. β-Xdoclint:(all|none|[-]group)[/access]β turns specific groups of checks in your documentation comments on or off π
So group can be any of these: accessibility, html, missing, reference, syntax. And access sets the minimum visibility level of the classes and members that -Xdoclint actually checks. Its values go (from most visible to least visible): public, protected, package, private. The default access level is private π
. When you prefix it with doclint:, the group names and all can be used with @SuppressWarnings to shush warnings about doc comments in parts of the code you're compiling. Want the full tea on these groups? Check the DocLint section of the javadoc command documentation. Heads up: -Xdoclint is disabled by default in javac π.
For example, this next one checks classes and members (with all groups of checks) that are protected and higher β which includes protected and public:
-Xdoclint:all/protected
And this one enables all groups of checks for all access levels, except it will not check for HTML errors for classes and members at package and higher (so package, protected and public):
-Xdoclint:all,-html/package
-Xdoclint/package:[-]packages(,[-]package)*β enables or disables checks in specific packages π¦
Each package is either the qualified name of a package, or a package name prefix followed by .*, which expands to all sub-packages of that package. You can prefix any package with a hyphen (-) to disable checks for that package or those packages. For more info, see the DocLint section of the javadoc command documentation.
-Xlintβ enables all recommended warnings β¨ In this release, enabling all available warnings is the recommended move, bestie.-Xlint:[-]key(,[-]key)*β enables and/or disables warning categories using one or more of the keys below, separated by commas π
The keys all and none enable or disable all categories (respectively); every other key enables its category, or disables it if it's preceded by a hyphen (-). Supported values for key are:
all: Enables all warning categories.auxiliaryclass: Warns about an auxiliary class that is hidden in a source file, and is used from other files.cast: Warns about the use of unnecessary casts.classfile: Warns about the issues related to classfile contents.dangling-doc-comments: Warns about extra or misplaced documentation comments near the beginning of a declaration.deprecation: Warns about the use of deprecated items.dep-ann: Warns about the items marked as deprecated in javadoc but without the@Deprecatedannotation.divzero: Warns about the division by the constant integer0.empty: Warns about an empty statement afterif.exports: Warns about the issues regarding module exports.fallthrough: Warns about the falling through from onecaseof aswitchstatement to the next.finally: Warns aboutfinallyclauses that do not terminate normally.identity: Warns about use of a value-based class where an identity class is expected.incubating: Warns about the use of incubating modules.lossy-conversions: Warns about possible lossy conversions in compound assignment.missing-explicit-ctor: Warns about missing explicit constructors in public and protected classes in exported packages.module: Warns about the module system-related issues.opens: Warns about the issues related to moduleopens.options: Warns about the issues relating to use of command line options.output-file-clash: Warns if any output file is overwritten during compilation. This can occur, for example, on case-insensitive filesystems.overloads: Warns about the issues related to method overloads.overrides: Warns about the issues related to method overrides.path: Warns about the invalid path elements on the command line.preview: Warns about the use of preview language features.processing: Warns about the issues related to annotation processing.rawtypes: Warns about the use of raw types.removal: Warns about the use of an API that has been marked for removal.restricted: Warns about the use of restricted methods.requires-automatic: Warns developers about the use of automatic modules inrequiresclauses.requires-transitive-automatic: Warns about automatic modules inrequires transitive.serial: Warns about the serializable classes that do not provide a serial version ID. Also warns about access to non-public members from a serializable element.static: Warns about the accessing a static member using an instance.strictfp: Warns about unnecessary use of thestrictfpmodifier.synchronization: Warns about synchronization attempts on instances of value-based classes. This key is a deprecated alias foridentity, which has the same uses and effects. Users are encouraged to use theidentitycategory for all future and existing uses ofsynchronization.text-blocks: Warns about inconsistent white space characters in text block indentation.this-escape: Warns about constructors leakingthisprior to subclass initialization.try: Warns about the issues relating to the use oftryblocks (that is, try-with-resources).unchecked: Warns about the unchecked operations.varargs: Warns about the potentially unsafe vararg methods.none: Disables all warning categories.
With the exception of all and none, the keys can be used with the @SuppressWarnings annotation to suppress warnings in a part of the source code being compiled. See Examples of Using -Xlint keys π
-Xmaxerrs numberβ sets the maximum number of errors to print π-Xmaxwarns numberβ sets the maximum number of warnings to print πΈ-Xpkginfo:[always, legacy, nonempty]β tellsjavacwhen and how to generatepackage-info.classfiles frompackage-info.javafiles π§
Pick one of these:
alwaysβ Generates apackage-info.classfile for everypackage-info.javafile. This option may be useful if you use a build system such as Ant, which checks that each.javafile has a corresponding.classfile.legacyβ Generates apackage-info.classfile only ifpackage-info.javacontains annotations. This option does not generate apackage-info.classfile ifpackage-info.javacontains only comments.
Note: Apackage-info.classfile might be generated but be empty if all the annotations in thepackage-info.javafile haveRetentionPolicy.SOURCE.
nonemptyβ Generates apackage-info.classfile only ifpackage-info.javacontains annotations withRetentionPolicy.CLASSorRetentionPolicy.RUNTIME.
-Xplugin:name argsβ specifies the name and optional arguments for a plug-in to be run π
If args are provided, name and args should be quoted or otherwise escape the whitespace characters between the name and all the arguments. For the deets on the API for a plugin, see the API documentation for jdk.compiler/com.sun.source.util.Plugin.
-Xprefer:[source, newer]β says which file to read when both a source file and a class file are found for an implicitly compiled class, using one of these options π See Searching for Module, Package and Type Declarations.-Xprefer:newer: Reads the newer of the source or class files for a type (default).-Xprefer:source: Reads the source file. Use-Xprefer:sourcewhen you want to be sure that any annotation processors can access annotations declared with a retention policy ofSOURCE.
-Xprintβ prints a textual representation of specified types for debugging purposes π
This does not perform annotation processing or compilation. The format of the output could change. (iykyk β don't build anything on top of it)
-XprintProcessorInfoβ prints information about which annotations a processor is asked to process π-XprintRoundsβ prints information about initial and subsequent annotation processing rounds β-Xstdout filenameβ sends compiler messages to the named file π¨ By default, compiler messages go toSystem.err.
πΈ ENVIRONMENT VARIABLES πΈ
Bestie, these are the environment variables that can change how javac behaves. They're lowkey important, so let's get into it π
π CLASSPATH
So here's the tea: if you don't pass --class-path (or any of its alternate forms), then the class path just defaults to whatever the CLASSPATH environment variable is set to, if it's set. But ngl, the recommendation is that you should not set this environment variable at all β instead use the --class-path option to give an explicit value for the class path whenever you actually need one. Like, be intentional with it, y'know? β¨
π¦ JDK_JAVAC_OPTIONS
Okay so this one's fun. The content of the JDK_JAVAC_OPTIONS environment variable gets split up by white-spaces ( ) or white-space characters (\n, \t, \r, or \f) and then prepended to the command line arguments passed to javac, as a list of arguments. It's giving "surprise bonus args" π
The encoding requirement for this environment variable is exactly the same as for the javac command line on the system. And the content of JDK_JAVAC_OPTIONS is treated in the same manner as what's specified in the command line. Same vibes, same rules π«Ά
Single quotes (') or double quotes (") can be used to enclose arguments that contain whitespace characters. All the content between the open quote and the first matching close quote gets preserved β you just remove the pair of quotes. And if a matching quote is not found? The launcher straight-up aborts with an error message π @files are supported, just like they are on the command line. But heads up: as with @files, use of a wildcard is not supported.
Here are some examples of quoting arguments that contain white spaces:
export JDK_JAVAC_OPTIONS='@"C:\white spaces\argfile"'
export JDK_JAVAC_OPTIONS='"@C:\white spaces\argfile"'
export JDK_JAVAC_OPTIONS='@C:\"white spaces"\argfile'
β¨ COMMAND-LINE ARGUMENT FILES β¨
An argument file can include command-line options and source file names, in any combination. The arguments within a file can be separated by spaces or new line characters. And if a file name has embedded spaces in it? Then wrap the whole file name in double quotation marks, easy π
Now, the important bit β file names within an argument file are relative to the current directory, not to the location of the argument file. Wildcards (*) are not allowed in these lists (so no specifying *.java, bestie, sorry π). Use of the at sign (@) to recursively interpret files is not supported either. And the -J options are not supported, because they get passed to the launcher, and the launcher does not support argument files. Periodt.
When you run the javac command, you pass in the path and name of each argument file with the at sign (@) as the leading character. When javac encounters an argument beginning with @, it expands the contents of that file into the argument list. It's like a little gift bag of args π
π Examples of Using javac @filename
β Single Argument File
You could use a single argument file named argfile to hold all the javac arguments:
javac @argfile
This argument file could contain the contents of both files shown in the following Two Argument Files example. Iconic of it, honestly π
π Two Argument Files
You can create two argument files: one for the javac options, and the other for the source file names. Note that the following lists have no line-continuation characters.
Create a file named options that contains the following β Linux and macOS:
-d classes
-g
-sourcepath /java/pubs/ws/1.3/src/share/classes
Windows:
-d classes
-g
-sourcepath C:\java\pubs\ws\1.3\src\share\classes
Create a file named sources that contains the following:
MyClass1.java
MyClass2.java
MyClass3.java
Then, run the javac command as follows:
javac @options @sources
π§ Argument Files with Paths
The argument files can have paths, but any file names inside the files are relative to the current working directory β so not path1 or path2, bestie:
javac @path1/options @path2/sources
π ARRANGEMENT OF SOURCE CODE π
Okay, so in the Java language, classes and interfaces can be organized into packages, and packages can be organized into modules. And javac expects the physical arrangement of source files in directories of the file system to actually mirror that organization of classes into packages, and packages into modules. Like, the file system is the map and the code has to follow it πΊοΈβ¨
It's a widely adopted convention that module names and package names begin with a lower-case letter, and that class names begin with an upper-case letter. Cute, right? π
πΈ Arrangement of Source Code for a Package
When classes and interfaces are organized into a package, the package is represented as a directory, and any subpackages are represented as subdirectories.
For example:
- The package
pis represented as a directory calledp. - The package
p.qβ that is, the subpackageqof packagepβ is represented as the subdirectoryqof directoryp. The directory tree representing packagep.qis thereforep\qon Windows, andp/qon other systems. - The package
p.q.ris represented as the directory treep\q\r(on Windows) orp/q/r(on other systems).
Within a directory or subdirectory, .java files represent classes and interfaces in the corresponding package or subpackage.
For example:
- The class
Xdeclared in packagepis represented by the fileX.javain thepdirectory. - The class
Ydeclared in packagep.qis represented by the fileY.javain theqsubdirectory of directoryp. - The class
Zdeclared in packagep.q.ris represented by the fileZ.javain thersubdirectory ofp\q(on Windows) orp/q(on other systems).
In some situations, it's convenient to split the code into separate directories, each structured as described above, and then hand javac the aggregate list of directories. Slay, flexible queen π
π Arrangement of Source Code for a Module
In the Java language, a module is a set of packages designed for reuse. In addition to .java files for classes and interfaces, each module has a source file called module-info.java which:
- declares the module's name;
- lists the packages exported by the module (to allow reuse by other modules);
- lists other modules required by the module (to reuse their exported packages).
When packages are organized into a module, the module is represented by one or more directories representing the packages in the module β one of which contains the module-info.java file. It may be convenient, but it is not required, to use a single directory, named after the module, to contain the module-info.java file alongside the directory tree which represents the packages in the module (i.e., the package hierarchy described above). The exact arrangement of source code for a module is typically dictated by the conventions adopted by a development environment (IDE) or build system. So like, don't stress about a "right" way β your IDE/builder runs the show π§
For example:
- The module
a.b.cmay be represented by the directorya.b.c, on all systems. - The module's declaration is represented by the file
module-info.javain thea.b.cdirectory. - If the module contains package
p.q.r, then thea.b.cdirectory contains the directory treep\q\r(on Windows) orp/q/r(on other systems).
The development environment may prescribe some directory hierarchy between the directory named for the module and the source files to be read by javac.
For example:
- The module
a.b.cmay be represented by the directorya.b.c - The module's declaration and the module's packages may be in some subdirectory of
a.b.c, such assrc\main\java(on Windows) orsrc/main/java(on other systems).
β¨ CONFIGURING A COMPILATION β¨
okay bestie, this section is literally the "how do I actually make javac do the thing" section. it walks you through configuring javac to do a basic compilation π«Ά
heads up: for extra details when you're compiling for a release of the platform that supports modules, go peek at Configuring the Module System (it's further down, no spoilers π ).
π Source Files
- Drop the source files you want compiled right on the command line. that's it, that's the vibe.
if there are no compilation errors, the matching class files get placed in the output directory. slay.
some systems may limit the amount you can put on a command line (rude π), and to work around those limits you can use argument files.
when compiling code for modules, you can also specify source files indirectly, by using the --module or -m option. sneaky but valid π
π Output Directory
- Use the
-doption to specify an output directory where the compiled class files go.
this will normally be organized in a package hierarchy β unless you're compiling source code from multiple modules, in which case it gets organized as a module hierarchy. different shape, same energy β¨
when the compilation has been completed, if you're compiling one or more modules, you can place the output directory on the module path for the Java launcher; otherwise, you can place the output directory on the class path for the Java launcher. pick the right lane, bestie π£οΈ
π Precompiled Code
the code you're compiling may refer to libraries beyond what the platform gives you. if so, you must place these libraries on the class path or module path. if the library code is not in a module, place it on the class path; if it is in a module, place it on the module path. iykyk π
--class-pathβ use this to specify libraries to be placed on the class path. locations on the class path should be organized in a package hierarchy. you can also use the alternate forms of the option:-classpathor-cp.--module-pathβ use this to specify libraries to be placed on the module path. locations on the module path should either be modules or directories of modules. you can also use an alternate form of the option:-p.
see Configuring the Module System for details on how to modify the default configuration of library modules π
note: the options for the class path and module path are not mutually exclusive, although it is not common to specify the class path when compiling code for one or more modules. so like, technically allowed, but read the room π
π¦ Additional Source Files
the code you're compiling may refer to types in additional source files that aren't specified on the command line. if so, you must put those source files on either the source path or module path. and listen β you can only specify one of these options: if you're not compiling code for a module, or if you're only compiling code for a single module, use the source path; if you're compiling code for multiple modules, use the module source path. choose wisely, no cap π
--source-pathβ use this to specify the locations of additional source files that may be read byjavac. locations on the source path should be organized in a package hierarchy. you can also use an alternate form of the option:-sourcepath.--module-source-pathβ use this one or more times to specify the location of additional source files in different modules that may be read byjavac, or when compiling source files in multiple modules. you can either specify the locations for each module individually, or you can organize the source files so that you can specify the locations all together. for more details, see The Module Source Path Option.
if you want to be able to refer to types in additional source files but do not want them to be compiled, use the -implicit option. main character behavior: referenced but not compiled π
note: if you're compiling code for multiple modules, you must always specify a module source path, and all source files specified on the command line must be in one of the directories on the module source path, or in a subdirectory thereof. this is not optional, bestie, it's the law π¨
πΈ Example of Compiling Multiple Source Files
this example compiles the Aloha.java, GutenTag.java, Hello.java, and Hi.java source files in the greetings package. iconic lineup fr fr β¨
Linux and macOS:
% javac greetings/*.java
% ls greetings
Aloha.class GutenTag.class Hello.class Hi.class
Aloha.java GutenTag.java Hello.java Hi.java
Windows:
C:\>javac greetings\*.java
C:\>dir greetings
Aloha.class GutenTag.class Hello.class Hi.class
Aloha.java GutenTag.java Hello.java Hi.java
π§ Example of Specifying a User Class Path
after changing one of the source files in the previous example, recompile it:
Linux and macOS:
pwd
/examples
javac greetings/Hi.java
Windows:
C:\>cd
\examples
C:\>javac greetings\Hi.java
because greetings.Hi refers to other classes in the greetings package, the compiler needs to find these other classes. the previous example works because the default user class path is the directory that contains the package directory. if you want to recompile this file without concern for which directory you're in, then add the examples directory to the user class path by setting CLASSPATH. this example uses the -classpath option π
Linux and macOS:
javac -classpath /examples /examples/greetings/Hi.java
Windows:
C:\>javac -classpath \examples \examples\greetings\Hi.java
if you change greetings.Hi to use a banner utility, then that utility also needs to be accessible through the user class path. teamwork makes the dream work π«Ά
Linux and macOS:
javac -classpath /examples:/lib/Banners.jar \
/examples/greetings/Hi.java
Windows:
C:\>javac -classpath \examples;\lib\Banners.jar ^
\examples\greetings\Hi.java
to execute a class in the greetings package, the program needs access to the greetings package, and to the classes that the greetings classes use. go give it what it needs π₯
Linux and macOS:
java -classpath /examples:/lib/Banners.jar greetings.Hi
Windows:
C:\>java -classpath \examples;\lib\Banners.jar greetings.Hi
π CONFIGURING THE MODULE SYSTEM π
now we're in module territory, bestie, put your thinking cap on π
if you want to include additional modules in your compilation, use the --add-modules option. this may be necessary when you're compiling code that is not in a module, or which is in an automatic module, and the code refers to API in the additional modules. basically: "hey compiler, these extras exist, please acknowledge them" π
if you want to restrict the set of modules in your compilation, use the --limit-modules option. this may be useful if you want to ensure that the code you're compiling is capable of running on a system with a limited set of modules installed. it's giving "will this even work on their machine" energy π
if you want to break encapsulation and specify that additional packages should be considered as exported from a module, use the --add-exports option. this may be useful when performing white-box testing; relying on access to internal API in production code is strongly discouraged. test it all you want, but ship it? no ma'am π«
if you want to specify that additional packages should be considered as required by a module, use the --add-reads option. this may be useful when performing white-box testing; relying on access to internal API in production code is strongly discouraged. same warning, same vibe, read it twice π
you can patch additional content into any module using the --patch-module option. see [Patching a Module] for more details. patchwork queen behavior π§΅
π SEARCHING FOR MODULE, PACKAGE AND TYPE DECLARATIONS π
Okay bestie, so here's the situation. To compile a source file, the compiler often needs info about a module or a type β but that declaration is literally nowhere in the source files you put on the command line. Where does it go looking? That's this whole section. Buckle up. π
javac needs type information for every class or interface used, extended, or implemented in the source file. And yes, that includes classes and interfaces that aren't even explicitly mentioned in your source file β the ones quietly providing info through inheritance. Sneaky little ancestors. π«Ά
For example, when you create a subclass of java.awt.Window, you're also using the ancestor classes of Window: java.awt.Container, java.awt.Component, and java.lang.Object. It's giving family tree energy. π³
When compiling code for a module, the compiler also needs to have the declaration of that module available. Non-negotiable, sorry.
A successful search may produce a class file, a source file, or both. And if both show up? That's when you use the -Xprefer option to tell the compiler which one to use. You're the main character, you decide. π
If a search finds and uses a source file, then by default javac compiles that source file. You can change that behavior with -implicit.
Now here's a lil plot twist π β the compiler might not clock that it needs some type info until after annotation processing completes. So when the type info is found in a source file and no -implicit option is specified, the compiler gives you a warning that the file is being compiled without being subject to annotation processing. To kill that warning, either:
- specify the file on the command line (so it will be subject to annotation processing), or
- use the
-implicitoption to specify whether or not class files should be generated for such source files.
The way javac locates the declarations of those types depends on whether the reference exists within code for a module or not. Very "depends on the vibe" of it all. β¨
π Searching Package Oriented Paths
When searching for a source or class file on a path made of package oriented locations, javac checks each location on the path in turn for the possible presence of the file.
The first occurrence of a particular file shadows (hides) any subsequent occurrences of like-named files. Periodt. And heads up: this shadowing does not affect any search for files with a different name.
This is honestly so convenient when you're searching for source files that may be grouped in different locations β think shared code, platform-specific code, and generated code. It's also useful when you're injecting alternate versions of a class file into a package, for debugging or other instrumentation reasons. π§
But it can also be dangerous β like when you put incompatible different versions of a library on the class path. Do not do that. I'm begging. π
π§ Searching Module Oriented Paths
Before scanning any module paths for any package or type declarations, javac will lazily scan the following paths and locations to figure out the modules that will be used in the compilation:
- The module source path (see the
--module-source-pathoption) - The path for upgradeable modules (see the
--upgrade-module-pathoption) - The system modules (see the
--systemoption) - The user module path (see the
--module-pathoption)
For any module, the first occurrence of the module during the scan completely shadows (hides) any subsequent appearance of a like-named module. First one ate, sorry to the rest. π
While locating the modules, javac can determine the packages exported by the module and associate with each module a package oriented path for the contents of the module. For any previously compiled module, this path will typically be a single entry β for either a directory or a file that provides an internal directory-like hierarchy, such as a JAR file. π«
So when it's searching for a type in a package that's known to be exported by a module, javac can locate the declaration directly and efficiently. Slay, no wasted steps.
π¦ Searching for the Declaration of a Module
If the module has been previously compiled, the module declaration lives in a file named module-info.class in the root of the package hierarchy for the content of the module.
If the module is one of those currently being compiled, the module declaration will be either:
- the file named
module-info.classin the root of the package hierarchy for the module in the class output directory, or - the file named
module-info.javain one of the locations on the source path or on the module source path for the module.
π΅οΈ Searching for the Declaration of a Type When the Reference is not in a Module
When searching for a type that's referenced in code that is not in a module, javac will look in these places, in order-ish:
- The platform classes (or the types in exported packages of the platform modules). (This is for compiled class files only.)
- Types in exported packages of any modules on the module path, if applicable. (This is for compiled class files only.)
- Types in packages on the class path and/or source path:
- If both are specified,
javaclooks for compiled class files on the class path and for source files on the source path. - If the class path is specified, but not source path,
javaclooks for both compiled class files and source files on the class path. - If the class path is not specified, it defaults to the current directory.
- If both are specified,
When looking for a type on the class path and/or source path, if both a compiled class file and a source file are found, the most recently modified file will be used by default. If the source file is newer, it will be compiled and may override any previously compiled version of the file. You can use the -Xprefer option to override the default behavior. π°οΈ
𧬠Searching for the Declaration of a Type When the Reference is in a Module
When searching for a type that's referenced in code in a module, javac will examine the declaration of the enclosing module to determine if the type is in a package that's exported from another module that is readable by the enclosing module.
If so, javac will simply and directly go to the definition of that module to find the definition of the required type. Unless the module is another one of the modules being compiled, javac will only look for compiled class files. In other words: javac will not look for source files in platform modules or modules on the module path. No source snooping in module-land, bestie. π
If the type being referenced is not in some other readable module, javac will examine the module being compiled to try and find the declaration of the type. It looks like this:
- Source files specified on the command line or on the source path or module source path.
- Previously compiled files in the output directory.
ποΈ DIRECTORY HIERARCHIES ποΈ
javac generally assumes that source files and compiled class files will be organized in a file system directory hierarchy, or in a type of file that supports an internal directory hierarchy, such as a JAR file. π«β¨
Three different kinds of hierarchy are supported: a package hierarchy, a module hierarchy, and a module source hierarchy.
While javac is fairly relaxed about the organization of source code β beyond the expectation that source will be organized in one or more package hierarchies, and it can generally accommodate organizations prescribed by development environments and build tools β Java tools in general, and javac and the Java launcher in particular, are more stringent regarding the organization of compiled class files, and will be organized in package hierarchies or module hierarchies, as appropriate. π€ The class files have standards.
The location of these hierarchies is specified to javac with command-line options, whose names typically end in "path", like --source-path or --class-path. Also as a general rule:
- path options whose name includes the word
module, like--module-path, are used to specify module hierarchies (although some module-related path options allow a package hierarchy to be specified on a per-module basis) - all other path options are used to specify package hierarchies
π Package Hierarchy
In a package hierarchy, directories and subdirectories represent the component parts of the package name, with the source file or compiled class file for a type being stored as a file with an extension of .java or .class in the most nested directory.
For example, in a package hierarchy, the source file for a class com.example.MyClass will be stored in the file:
com/example/MyClass.java
π§© Module Hierarchy
In a module hierarchy, the first level of directories are named for the modules in the hierarchy; within each of those directories, the contents of the module are organized in package hierarchies.
For example, in a module hierarchy, the compiled class file for a type called com.example.MyClass in a module called my.library will be stored in:
my.library/com/example/MyClass.class
The various output directories used by javac β the class output directory, the source output directory, and native header output directory β will all be organized in a module hierarchy when multiple modules are being compiled. Consistency icon behavior. π
πΈ Module Source Hierarchy
Although the source for each individual module should always be organized in a package hierarchy, it may be convenient to group those hierarchies into a module source hierarchy. This is similar to a module hierarchy, except that there may be intervening directories between the directory for the module and the directory that is the root of the package hierarchy for the source code of the module. π¦
For example, in a module source hierarchy, the source file for a type called com.example.MyClass in a module called my.library may be stored in a file such as:
my.library/src/main/java/com/example/MyClass.java
See? Intervening directories. It's giving organized chaos and honestly we respect it. π
β¨ THE MODULE SOURCE PATH OPTION β¨
okay so <pink>--module-source-path</pink> comes in two forms, and bestie you gotta know both:
- a module-specific</> form, where you hand it a package path for each module that has code to compile
- a module-pattern</> form, where the source path for each module is spelled out by a pattern
the module-specific one is lowkey simpler when you're only juggling a small number of modules. the module-pattern one is highkey more convenient when you've got a ton of modules and they're organized all regular-like, in a way a pattern can describe. β¨
you can give multiple instances of --module-source-path, each one using either the module-pattern form or the module-specific form β but only within these limits, bestie:
- the module-pattern form may be used at most once
- the module-specific form may be used at most once for any given module
and if you use the module-specific form for any module, the associated search path overrides any path that might otherwise have been inferred from the module-pattern form. no cap, it wins. π
π Module-specific form
this form lets you give an explicit search path for any specific module. it's shaped like this:
--module-source-pathmodule-name=file-path (`path-separator file-path)*
the path separator character is ; on Windows, and : otherwise. πͺπ§
Note: this is similar to the form used for the --patch-module option.
π Module-pattern form
this form lets you concisely spec the module source path for any number of modules organized in a regular manner.
--module-source-pathpattern
the pattern is defined by these rules, applied in order:
- the argument is considered to be a series of segments separated by the path separator character (
;on Windows, and:otherwise). - each segment containing curly braces of the form
string1{alt1 ( ,alt2 )* } string2
is considered to be replaced by a series of segments formed by "expanding" the braces:
string1 alt1 string2
string1 alt2 string2
and so on...
the braces may be nested. π
this rule is applied for all such usages of braces.
- each segment must have at most one asterisk (
*). if a segment does not contain an asterisk, it's considered to be as though the file separator character and an asterisk are appended.
for any module M, the source path for that module is formed from the series of segments you get by substituting the module name M for the asterisk in each segment.
Note: in this context the asterisk is just used as a special marker, to denote the position in the path of the module name. it should not be confused with the use of * as a file name wildcard character, as found on most operating systems. don't do that to yourself π
πΈ PATCHING MODULES πΈ
javac lets you patch any content β whether in source or compiled form β into any module using the --patch-module option. and why would you even want that? glad you asked: to compile alternative implementations of a class you're gonna patch at runtime into a JVM, or to inject additional classes into the module, like when you're testing. π§ͺ
the option is shaped like this:
--patch-modulemodule-name=file-path (`path-separator file-path )*
the path separator character is ; on Windows, and : otherwise. the paths you give for the module must specify the root of a package hierarchy for the contents of the module. π³
the option may be given at most once for any given module. any content on the path will hide any like-named content later in the path and in the patched module. so like, first one wins, bye. π
when patching source code into more than one module, the --module-source-path must also be used, so that the output directory is organized in a module hierarchy and is capable of holding the compiled class files for the modules being compiled. π«Ά
β ANNOTATION PROCESSING β
the javac command provides direct support for annotation processing. β¨
the API for annotation processors is defined in the javax.annotation.processing and javax.lang.model packages and subpackages.
π¦ How Annotation Processing Works
annotation processing is requested by using an option to configure annotation processing, such as -processor, --processor-path, --processor-module-path, or by explicitly enabling processing with the -proc:full or -proc:only options. annotation processing is disabled using the -proc:none option. π«
if annotation processing is requested, the compiler searches for any annotation processors that are available.
the search path can be specified with the -processorpath option. if no path is specified, then 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 is called. a processor can claim the annotations it processes, in which case no further attempt is made to find any processors for those annotations. after all of the annotations are claimed, the compiler does not search for additional processors. periodt. π
if any processors generate new source files, then another round of annotation processing occurs: any newly generated source files are scanned, and the annotations processed as before. any processors called on previous rounds are also called on all subsequent rounds. this keeps going until no new source files are generated. π
after a round occurs where no new source files are generated, the annotation processors are called one last time, to give them a chance to complete any remaining work. finally, unless the -proc:only option is used, the compiler compiles the original and all generated source files. π¬
if you use an annotation processor that generates additional source files to be included in the compilation, you can specify a default module to be used for the newly generated files, for use when a module declaration is not also generated. in this case, use the --default-module-for-created-files option. π
π§ Compilation Environment and Runtime Environment.
the declarations in source files and previously compiled class files are analyzed by javac in a compilation environment that is distinct from the runtime environment used to execute javac itself. and yeah, there's a deliberate similarity between many javac options and like-named options for the Java launcher β --class-path, --module-path, and so on β but bestie it is important to understand that in general the javac options just affect the environment in which the source files are compiled, and do not affect the operation of javac itself. two different vibes, two different worlds. πβ¨
the distinction between the compilation environment and runtime environment is significant when it comes to using annotation processors. even though annotation processors process elements (declarations) that exist in the compilation environment, the annotation processor itself is executed in the runtime environment. if an annotation processor has dependencies on libraries that aren't in modules, the libraries can be placed, along with the annotation processor itself, on the processor path. (see the --processor-path option.) if the annotation processor and its dependencies are in modules, you should use the processor module path instead. (see the --processor-module-path option.) when those are insufficient, it may be necessary to provide further configuration of the runtime environment. you can do that in two ways:
- if
javacis invoked from the command line, options can be passed to the underlying runtime by prefixing the option with-J. π Ή - you can start an instance of a Java Virtual Machine directly and use command line options and API to configure an environment in which
javaccan be invoked via one of its APIs.
π₯ COMPILING FOR EARLIER RELEASES OF THE PLATFORM π₯
javac can compile code that's meant to be used on other releases of the platform, using either the --release option, or the --source/-source and --target/-target options, together with additional options to specify the platform classes. π°οΈ
depending on the desired platform release, there are some restrictions on some of the options you can use.
- when compiling for JDK 8 and earlier releases, you cannot use any option that is intended for use with the module system. this includes all of the following options:
--module-source-path,--upgrade-module-path,--system,--module-path,--add-modules,--add-exports,--add-opens,--add-reads,--limit-modules,--patch-module
if you use the --source/-source or --target/-target options, you should also set the appropriate platform classes using the boot class path family of options. π₯Ύ
- when compiling for JDK 9 and later releases, you cannot use any option that is intended to configure the boot class path. this includes all of the following options:
-Xbootclasspath/p:,-Xbootclasspath,-Xbootclasspath/a:,-endorseddirs,-Djava.endorsed.dirs,-extdirs,-Djava.ext.dirs,-profile
if you use the --source/-source or --target/-target options, you should also set the appropriate platform classes using the --system option to give the location of an appropriate installed release of JDK. π
when using the --release option, only the supported documented API for that release may be used; you cannot use any options to break encapsulation to access any internal classes. no sneaky backdoors, bestie. π
ββοΈ
π APIS π
the javac compiler can be invoked using an API in three different ways:
The Java Compiler API
this provides the most flexible way to invoke the compiler, including the ability to compile source files provided in memory buffers or other non-standard file systems. π§ π
The ToolProvider API
a ToolProvider for javac can be obtained by calling ToolProvider.findFirst("javac"). this returns an object with the equivalent functionality of the command-line tool.
Note: this API should not be confused with the like-named API in the javax.tools package. π
The javac Legacy API
this API is retained for backward compatibility only. all new code should use either the Java Compiler API or the ToolProvider API. it's giving legacy, it's giving "still here for the old heads". π«Ά
Note: all other classes and methods found in a package with names that start withcom.sun.tools.javac(subpackages ofcom.sun.tools.javac) are strictly internal and subject to change at any time. so like, don't build your whole life on them, mwah. π
π EXAMPLES OF USING -XLINT KEYS π
cast β warns about unnecessary and redundant casts, for example:
classfile
OK so this one warns you about stuff related to class file contents π like if the bytes are giving something sus, bestie gets a heads up.
deprecation
Warns you when you're out here using deprecated items π like, sweetie, that API has a "no longer it" note on it. Example:
java.util.Date myDate = new java.util.Date();
int currentDay = myDate.getDay();
And then the compiler hits you with:
The method java.util.Date.getDay has been deprecated since JDK 1.1.
dep-ann
Warns about items that are documented with the @deprecated Javadoc comment but do not have the @Deprecated annotation β¨ like, you said it in the docs but not in the code, pick a lane. Example:
/**
* @deprecated As of Java SE 7, replaced by {@link #newMethod()}
*/
public static void deprecatedMethod() { }
public static void newMethod() { }
divzero
Warns about division by the constant integer 0 π like bestie that's literally just math screaming. Example:
int divideByZero = 42 / 0;
empty
Warns about empty statements after if statements π« that stray semicolon is doing absolutely nothing and the compiler noticed. Example:
class E {
void m() {
if (true) ;
}
}
fallthrough
Checks switch blocks for fall-through cases and slides a warning message your way for any that it finds π. So what even is a fall-through case? It's a case in a switch block β any case that isn't the last one in the block β whose code doesn't include a break statement, which lets code execution fall through from that case into the next one π. Example: the code following the case 1 label in this switch block doesn't end with a break statement:
switch (x) {
case 1:
System.out.println("1");
// No break statement here.
case 2:
System.out.println("2");
}
If the -Xlint:fallthrough option was used when compiling this code, then the compiler emits a warning about possible fall-through into case, with the line number of the case in question π.
finally
Warns about finally clauses that cannot be completed normally, fr fr. 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 the finally block in this example β οΈ. When the int method is called, it returns a value of 0. A finally block executes when the try block exits. In this example, when control is transferred to the catch block, the int method exits. However, the finally block must execute, so it's executed, even though control was transferred outside the method π.
options
Warns about issues that are related to the use of command-line options. Peep Compiling for Earlier Releases of the Platform for the tea π΅.
overrides
Warns about issues related to method overrides π. For example, consider the following two classes:
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:
warning: [override] varargsMethod(String[]) in ClassWithOverridingMethod
overrides varargsMethod(String...) in ClassWithVarargsMethod; overriding
method is missing '...'
When the compiler encounters a varargs method, it translates the varargs formal parameter into an array π. In the method ClassWithVarargsMethod.varargsMethod, the compiler translates the varargs formal parameter String... s to the formal parameter String[] s, an array that matches the formal parameter of the method ClassWithOverridingMethod.varargsMethod. Consequently, this example compiles π.
path
Warns about invalid path elements and nonexistent path directories on the command line (with regard to the class path, the source path, and other paths) π£οΈ. And heads up: such warnings cannot be suppressed with the @SuppressWarnings annotation π
. For example:
- Linux and macOS:
javac -Xlint:path -classpath /nonexistentpath Example.java - Windows:
javac -Xlint:path -classpath C:\nonexistentpath Example.java
processing
Warns about issues related to annotation processing β¨. The compiler generates this warning when you have a class that has an annotation, and you use an annotation processor that cannot handle that type of annotation. For example, the following is a simple annotation processor:
Source file 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.java
When the compiler runs the annotation processor against the source file AnnosWithoutProcessors.java, it generates the following warning:
warning: [processing] No processor claimed any of these annotations: Anno
To resolve this issue, you can rename the annotation defined and used in the class AnnosWithoutProcessors from Anno to NotAnno π.
rawtypes
Warns about unchecked operations on raw types π¬. The following statement generates a rawtypes warning:
void countElements(List l) { ... }
The following example does not generate a rawtypes warning:
void countElements(List<?> l) { ... }
List is a raw type. However, List<?> is an unbounded wildcard parameterized type πΈ. Because List is a parameterized interface, always specify its type argument. In this example, the List formal argument is specified with an unbounded wildcard (?) as its formal type parameter, which means that the countElements method can accept any instantiation of the List interface β¨.
serial
Warns about missing 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:
warning: [serial] serializable class PersistentTime has no definition of
serialVersionUID
If a serializable class does not explicitly declare a field named serialVersionUID, then the serialization runtime environment calculates a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification π. However, it's strongly recommended that all serializable classes explicitly declare serialVersionUID values because the default process of computing serialVersionUID values is highly sensitive to class details that can vary depending on compiler implementations π. As a result, this might cause an unexpected InvalidClassExceptions during deserialization π. To guarantee a consistent serialVersionUID value across different Java compiler implementations, a serializable class must declare an explicit serialVersionUID value. Periodt π.
static
Warns about issues relating to the use of static variables, for example:
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 expression
To resolve this issue, you can call the static method m1 as follows:
XLintStatic.m1();
Alternately, you can remove the static keyword from the declaration of the method m1 π«Ά.
this-escape
Warns about constructors leaking this prior to subclass initialization π³ like bestie that's the constructor handing out its own address before the subclass is even ready β main character behavior that is not it. For example, this class:
public class MyClass {
public MyClass() {
System.out.println(this.hashCode());
}
}
generates the following warning:
MyClass.java:3: warning: [this-escape] possible 'this' escape
before subclass is fully initialized
System.out.println(this.hashCode());
^
this-escape is the one that's like... bestie, the object isn't even DONE yet and you're already handing out keys to it? π This warning slides in whenever a constructor does something that might result in a subclass method being invoked before the constructor returns. And in those cases the subclass method would be operating on an incompletely initialized instance β it's giving "showing up to the party before the decorations are up" π.
So in the example up there, a subclass of MyClass that overrides hashCode() to incorporate its own fields would likely produce an incorrect result when invoked as shown. Yeah. Not cute.
Real talk though: warnings are only generated if a subclass could exist that is outside of the current module (or package, if no module) being compiled. So, for example, constructors in final and non-public classes do not generate warnings. Slay, final classes stay unbothered π.
tryβ Warns about issues relating to the use oftryblocks, including try-with-resources statements β¨. For example, a warning is generated for the following statement because the resourceacdeclared in thetryblock is not used:
try ( AutoCloseable ac = getResource() ) { // do nothing}
Like... you opened the resource and did NOTHING with it? The audacity. The waste. The compiler noticed π«Ά
uncheckedβ Gives more detail for unchecked conversion warnings that are mandated by the Java Language Specification, for example:
List l = new ArrayList<Number>();
List<String> ls = l; // unchecked warning
Okay so lemme explain this one because it's iconic and also a whole saga π. During type erasure, the types ArrayList<Number> and List<String> become ArrayList and List, respectively. The ls variable has the parameterized type List<String>. When the List referenced by l is assigned to ls, the compiler generates an unchecked warning. At compile time, the compiler and JVM cannot determine whether l refers to a List<String> type. In this case, l does not refer to a List<String> type. As a result, heap pollution occurs π±.
A heap pollution situation occurs when the 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 backward compatibility with releases 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. Blame history, not the compiler bestie π
varargsβ Warns about unsafe use of variable arguments (varargs) methods, in particular, those that contain non-reifiable arguments, for example:
public class ArrayBuilder {
public static <T> void addToList (List<T> listArg, T... elements) {
for (T x : elements) {
listArg.add(x);
}
}
}
A non-reifiable type is a type whose type information is not fully available at runtime. The compiler generates the following warning for the definition of the method ArrayBuilder.addToList:
warning: [varargs] Possible heap pollution from parameterized vararg type T
When 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's a possibility of heap pollution. It's giving "I tried my best and my best was erasure" π§
π final vibe check: every one of these keys is just the compiler being a very attentive bestie who clocked the situation before it became a problem. Listen to her. She's literally never wrong.
β¨ and that's the whole page, bestie!! β¨ You made it to the end, which honestly? Main character energy π. This absolute unit of a manpage came from JDK 25.0.5.0.3, dated 2026, and it's filed under JAVAC(1) β so like, if you ever forget a flag, you know exactly where to come back to. Go forth and compile, queen ππ
π¦ where this page comes from
- arch rolling: jdk25-openjdk 25.0.5.0.3.u1-1 Β· LicenseRef-Java
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms