javac(1)

๐Ÿ“ฆ version 11.0.20.1.1, in centos-stream 9

๐Ÿ’– javac(1) โ€” Basic Tools, bestie ๐Ÿ’–

Okay so this is the javac(1) page from the Basic Tools crew, and it's literally the main character of "turn my Java into bytecode." Let's get into it. ๐Ÿซถ


โœจ NAME โœจ

javac โ€” reads Java class and interface definitions and compiles them into bytecode and class files. periodt. ๐Ÿ’…


๐ŸŒธ SYNOPSIS ๐ŸŒธ

javac [ options ] [ sourcefiles ] [ classes] [ @argfiles ]

Arguments can be in any order:

  • options โ€” command-line options. See Options.
  • sourcefiles โ€” one or more source files to be compiled (such as MyClass.java).
  • classes โ€” one or more classes to be processed for annotations (such as MyPackage.MyClass).
  • @argfiles โ€” one or more files that list options and source files. The -J options are not allowed in these files. See Command-Line Argument Files.

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

The javac command reads class and interface definitions, written in the Java programming language, and compiles them into bytecode class files. It can also process annotations in Java source files and classes. No cap. โœจ

There are two ways to pass source code file names to javac:

  • For a small number of source files, list the file names on the command line.
  • For a large number of source files, list the file names in a file that is separated by blanks or line breaks. Use the list file name preceded by an at sign (@) with the javac command.

Source code file names must have .java suffixes, class file names must have .class suffixes, and both source and class files must have root names that identify the class. For example, a class called MyClass would be written in a source file called MyClass.java and compiled into a bytecode class file called MyClass.class. Slay. ๐ŸŽ€

Inner class definitions produce additional class files. These class files have names that combine the inner and outer class names, such as MyClass$MyInnerClass.class.

Arrange source files in a directory tree that reflects their package tree. For example, if all of your source files are in /workspace, then put the source code for com.mysoft.mypack.MyClass in /workspace/com/mysoft/mypack/MyClass.java.

By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d option. ๐Ÿ’œ


โœจ OPTIONS โœจ

The compiler has a set of standard options that are supported on the current development environment. An additional set of nonstandard options are specific to the current virtual machine and compiler implementations and are subject to change in the future. Nonstandard options begin with the -X option. iykyk. ๐Ÿ”ฅ

  • See also Cross-Compilation Options
  • See also Nonstandard Options

๐Ÿ‘‘ STANDARD OPTIONS ๐Ÿ‘‘

  • -Akey[=value] โ€” specifies options to pass to annotation processors. These options are not interpreted by javac directly, but are made available for use by individual processors. The key value should be one or more identifiers separated by a dot (.).
  • -cp path or -classpath path โ€” specifies where to find user class files, and (optionally) annotation processors and source files. This class path overrides the user class path in the CLASSPATH environment variable. If neither CLASSPATH, -cp nor -classpath is specified, then the user class path is the current directory. See Setting the Class Path.

If the -sourcepath option is not specified, then the user class path is also searched for source files.

If the -processorpath option is not specified, then the class path is also searched for annotation processors.

  • -Djava.ext.dirs=directories โ€” overrides the location of installed extensions.
  • -Djava.endorsed.dirs=directories โ€” overrides the location of the endorsed standards path.
  • -d directory โ€” sets the destination directory for class files. The directory must already exist because javac does not create it. If a class is part of a package, then javac puts the class file in a subdirectory that reflects the package name and creates directories as needed.

If you specify -d/home/myclasses and the class is called com.mypackage.MyClass, then the class file is /home/myclasses/com/mypackage/MyClass.class.

If the -d option is not specified, then javac puts each class file in the same directory as the source file from which it was generated.

Note: The directory specified by the -d option is not automatically added to your user class path. ๐Ÿ™ˆ
  • -deprecation โ€” shows a description of each use or override of a deprecated member or class. Without the -deprecation option, javac shows a summary of the source files that use or override deprecated members or classes. The -deprecation option is shorthand for -Xlint:deprecation.
  • -encoding encoding โ€” sets the source file encoding name, such as EUC-JP and UTF-8. If the -encoding option is not specified, then the platform default converter is used.
  • -endorseddirs directories โ€” overrides the location of the endorsed standards path.
  • -extdirs directories โ€” overrides the location of the ext directory. The directories variable is a colon-separated list of directories. 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 cross-compiling (compiling classes against bootstrap and extension classes of a different Java platform implementation), then this option specifies the directories that contain the extension classes. See Cross-Compilation Options for more information.

  • -g โ€” generates all debugging information, including local variables. By default, only line number and source file information is generated.
  • -g:none โ€” does not generate any debugging information.
  • -g:[keyword list] โ€” generates only some kinds of debugging information, specified by 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 โ€” prints a synopsis of standard options.
  • -implicit:[class, none] โ€” controls the generation of class files for implicitly loaded source files. To automatically generate class files, use -implicit:class. To suppress class file generation, use -implicit:none. If this option is not specified, then the default is to automatically generate class files. In this case, the compiler issues a warning if any such class files are generated when also doing annotation processing. The warning is not issued when the -implicit option is set explicitly. See Searching for Types.
  • -Joption โ€” passes option to the Java Virtual Machine (JVM), where option is one of the options described on the reference page for the Java launcher. For example, -J-Xms48m sets the startup memory to 48 MB. See java(1).
Note: The CLASSPATH, -classpath, -bootclasspath, and -extdirs options do not specify the classes used to run javac. 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 -J option to pass options through to the underlying Java launcher. ๐Ÿ˜ญ
  • -nowarn โ€” disables warning messages. This option operates the same as the -Xlint:none option.
  • -parameters โ€” stores formal parameter names of constructors and methods in the generated class file so that the method java.lang.reflect.Executable.getParameters from the Reflection API can retrieve them.
  • -proc: [none, only] โ€” controls whether annotation processing and compilation are done. -proc:none means that compilation takes place without annotation processing. -proc:only means that only annotation processing is done, without any subsequent compilation.
  • -processor class1 [,class2,class3...] โ€” names of the annotation processors to run. This bypasses the default discovery process.
  • -processorpath path โ€” specifies where to find annotation processors. If this option is not used, then the class path is searched for processors.
  • -s dir โ€” specifies the directory where to place the generated source files. The directory must already exist because javac does not create it. If a class is part of a package, then the compiler puts the source file in a subdirectory that reflects the package name and creates directories as needed.

If you specify -s /home/mysrc and the class is called com.mypackage.MyClass, then the source file is put in /home/mysrc/com/mypackage/MyClass.java.

  • -source release โ€” specifies the version of source code accepted. The following values for release are allowed:
    • 1.3 โ€” the compiler does not support assertions, generics, or other language features introduced after Java SE 1.3.
    • 1.4 โ€” the compiler accepts code containing assertions, which were introduced in Java SE 1.4.
    • 1.5 โ€” the compiler accepts code containing generics and other language features introduced in Java SE 5.
    • 5 โ€” synonym for 1.5.
    • 1.6 โ€” no language changes were introduced in Java SE 6. However, encoding errors in source files are now reported as errors instead of warnings as in earlier releases of Java Platform, Standard Edition.
    • 6 โ€” synonym for 1.6.
    • 1.7 โ€” the compiler accepts code with features introduced in Java SE 7.
    • 7 โ€” synonym for 1.7.
    • 1.8 โ€” this is the default value. The compiler accepts code with features introduced in Java SE 8.
    • 8 โ€” synonym for 1.8.
  • -sourcepath sourcepath โ€” specifies the source code path to search for class or interface definitions. As with the user class path, source path entries are separated by colons (:) on Oracle Solaris and semicolons on Windows and can be directories, JAR archives, or ZIP archives. If packages are used, then the local path name within the directory or archive must reflect the package name.
Note: Classes found through the class path might be recompiled when their source files are also found. See Searching for Types. ๐Ÿ’€
  • -verbose โ€” turns on verbose output, so you get the tea on every class loaded and every source file compiled. it's giving "tell me everything" ๐Ÿ’…
  • -version โ€” prints release information. that's it, that's the whole vibe โœจ
  • -werror โ€” terminates compilation when warnings occur. warnings become full-on showstoppers, no cap ๐Ÿ˜ญ
  • -X โ€” displays information about nonstandard options and exits. a little peek behind the curtain ๐ŸŽ€

๐Ÿฆ‹ CROSS-COMPILATION OPTIONS ๐Ÿฆ‹

okay so by default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. but javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. and bestie, it is important to use the -bootclasspath and -extdirs options when cross-compiling. like, not optional-important. important-important ๐Ÿซถ

  • -target version โ€” generates class files that target a specified release of the virtual machine. class files will run on the specified target and on later releases, but not on earlier releases of the JVM. valid targets are 1.1, 1.2, 1.3, 1.4, 1.5 (also 5), 1.6 (also 6), 1.7 (also 7), and 1.8 (also 8).

the default for the -target option depends on the value of the -source option:

  • If the -source option is not specified, then the value of the -target option is 1.8
  • If the -source option is 1.2, then the value of the -target option is 1.4
  • If the -source option is 1.3, then the value of the -target option is 1.4
  • If the -source option is 1.5, then the value of the -target option is 1.8
  • If the -source option is 1.6, then the value of the -target option is 1.8
  • If the -source option is 1.7, then the value of the -target option is 1.8
  • For all other values of the -source option, the value of the -target option is the value of the -source option.
  • -bootclasspath bootclasspath โ€” cross-compiles against the specified set of boot classes. same deal as the user class path: boot class path entries are separated by colons (:) and can be directories, JAR archives, or ZIP archives. ๐Ÿ—‚๏ธ

๐ŸŒธ COMPACT PROFILE OPTION ๐ŸŒธ

beginning with JDK 8, the javac compiler supports compact profiles. with compact profiles, applications that do not require the entire Java platform can be deployed and run with a smaller footprint. the compact profiles feature could be used to shorten the download time for applications from app stores. this feature makes for more compact deployment of Java applications that bundle the JRE. it's also useful in small devices โ€” tiny tech rights ๐Ÿงš

the supported profile values are compact1, compact2, and compact3. these are additive layers. each higher-numbered compact profile contains all of the APIs in profiles with smaller number names. so compact3 is the liddol overachiever of the group ๐Ÿ‘‘

  • -profile โ€” when using compact profiles, this option specifies the profile name when compiling. for example:

javac -profile compact1 Hello.java

javac does not compile source code that uses any Java SE APIs that is not in the specified profile. here's an example of the error message that results from attempting to compile such source code:

cd jdk1.8.0/bin
./javac -profile compact1 Paint.java
Paint.java:5: error: Applet is not available in profile 'compact1'
import java.applet.Applet;

in this example, you can correct the error by modifying the source to not use the Applet class. you could also correct the error by compiling without the -profile option. then the compilation would be run against the full set of Java SE APIs. (none of the compact profiles include the Applet class. rude but true ๐Ÿ’€)

an alternative way to compile with compact profiles is to use the -bootclasspath option to specify a path to an rt.jar file that specifies a profile's image. using the -profile option instead does not require a profile image to be present on the system at compile time. this is useful when cross-compiling. โœจ


๐Ÿ’œ NONSTANDARD OPTIONS ๐Ÿ’œ

  • -Xbootclasspath/p: path โ€” adds a suffix to the bootstrap class path.
  • -Xbootclasspath/a: path โ€” adds a prefix to the bootstrap class path.
  • -Xbootclasspath/: path โ€” overrides the location of the bootstrap class files.
  • -Xdoclint:[-] group [/access] โ€” enables or disables specific groups of checks, where group is one of the following values: accessibility, syntax, reference, html or missing. for more info about these groups of checks, see the -Xdoclint option of the javadoc command. heads up: the -Xdoclint option is disabled by default in the javac command ๐Ÿ™ˆ

the variable access specifies the minimum visibility level of classes and members that the -Xdoclint option checks. it can have one of the following values (in order of most to least visible): public, protected, package and private. for example, the following option checks classes and members (with all groups of checks) that have the access level protected and higher (which includes protected, package and public):

-Xdoclint:all/protected

the following option enables all groups of checks for all access levels, except it will not check for HTML errors for classes and members that have access level package and higher (which includes package and public):

-Xdoclint:all,-html/package
  • -Xdoclint:none โ€” disables all groups of checks.
  • -Xdoclint:all[/ access ] โ€” enables all groups of checks.
  • -Xlint โ€” enables all recommended warnings. in this release, enabling all available warnings is recommended. yes bestie, turn them all on ๐Ÿ’…
  • -Xlint:all โ€” enables all recommended warnings. in this release, enabling all available warnings is recommended. (same energy, spelled out)
  • -Xlint:none โ€” disables all warnings. silence. peace. ๐Ÿ•ฏ๏ธ
  • -Xlint: name โ€” disables warning name. see "Enable or Disable Warnings with the -Xlint Option" for a list of warnings you can disable with this option.
  • -Xlint:- name โ€” disables warning name. see "Enable or Disable Warnings with the -Xlint Option" with the -Xlint option to get a list of warnings that you can disable with this option.
  • -Xmaxerrs number โ€” sets the maximum number of errors to print. keeps the chaos contained ๐Ÿ˜Œ
  • -Xmaxwarns number โ€” sets the maximum number of warnings to print.
  • -Xstdout filename โ€” sends compiler messages to the named file. by default, compiler messages go to System.err.
  • -Xprefer:[newer,source] โ€” specifies which file to read when both a source file and class file are found for a type. (see "Searching for Types".) if the -Xprefer:newer option is used, then it reads the newer of the source or class file for a type (default). if the -Xprefer:source option is used, then it reads the source file. use -Xprefer:source when you want to be sure that any annotation processors can access annotations declared with a retention policy of SOURCE. ๐Ÿ‘€
  • -Xpkginfo:[always,legacy,nonempty] โ€” control whether javac generates package-info.class files from package-info.java files. possible mode arguments for this option include the following.
    • always โ€” always generate a package-info.class file for every package-info.java file. this option may be useful if you use a build system such as Ant, which checks that each .java file has a corresponding .class file.
    • legacy โ€” generate a package-info.class file only if package-info.java contains annotations. don't generate a package-info.class file if package-info.java only contains comments.
note: a package-info.class file might be generated but be empty if all the annotations in the package-info.java file have RetentionPolicy.SOURCE.
  • nonempty โ€” generate a package-info.class file only if package-info.java contains annotations with RetentionPolicy.CLASS or RetentionPolicy.RUNTIME.
  • -Xprint โ€” prints a textual representation of specified types for debugging purposes. performs neither annotation processing nor compilation. the format of the output could change. (so don't go building your whole life on it, bestie ๐Ÿซ )
  • -XprintProcessorInfo โ€” prints information about which annotations a processor is asked to process.
  • -XprintRounds โ€” prints information about initial and subsequent annotation processing rounds.

๐ŸŽ€ ENABLE OR DISABLE WARNINGS WITH THE -XLINT OPTION ๐ŸŽ€

enable warning name with the -Xlint:name option, where name is one of the following warning names. note that you can disable a warning with the -Xlint:-name: option.

  • cast โ€” warns about unnecessary and redundant casts, for example:
String s = (String) "Hello!"
  • classfile โ€” warns about issues related to class file contents.
  • deprecation โ€” warns about the use of deprecated items, for example:
java.util.Date myDate = new java.util.Date();
int currentDay = myDate.getDay();

the method java.util.Date.getDay has been deprecated since JDK 1.1 ๐Ÿซก

  • dep-ann โ€” warns about items that are documented with an @deprecated Javadoc comment, but do not have a @Deprecated annotation, for example:
/**
  * @deprecated As of Java SE 7, replaced by {@link #newMethod()}
  */
public static void deprecatedMethood() { }
public static void newMethod() { }
  • divzero โ€” warns about division by the constant integer 0, for example:
int divideByZero = 42 / 0;
  • empty โ€” warns about empty statements after if statements, for example:
class E {
    void m() {
         if (true) ;
    }
}
  • fallthrough โ€” checks the switch blocks for fall-through cases and provides a warning message for any that are found. fall-through cases are cases in a switch block, other than the last case in the block, whose code does not include a break statement, allowing code execution to fall through from that case to the next case. for example, the code following the case 1 label in this switch block does not 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 you about finally clauses that literally cannot complete normally, bestie. Like this one right here:

public static int m() {
  try {
     throw new NullPointerException();
  }  catch (NullPointerException(); {
     System.err.println("Caught NullPointerException.");
     return 1;
   } finally {
     return 0;
   }
  }

The compiler generates a warning for the finally block in this example. So what actually happens? 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. But the finally block must execute, so it is executed โ€” even though control was transferred outside the method. ๐Ÿ˜ญ the drama of it all.

๐Ÿซถ options ๐Ÿซถ

Warns about issues that are related to the use of command-line options. See Cross-Compilation Options.

๐Ÿ‘‘ overrides ๐Ÿ‘‘

Warns about issues regarding method overrides. For example, consider these 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 โ€” which matches the formal parameter of the method ClassWithOverridingMethod.varargsMethod. Consequently, this example compiles. Slay, honestly.

๐ŸŒˆ 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). Heads up though: these warnings cannot be suppressed with the @SuppressWarnings annotation. Example:

javac -Xlint:path -classpath /nonexistentpath Example.java

๐Ÿงš processing ๐Ÿงš

Warns about issues regarding 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 exception. For example, the following is a simple annotation processor:

Source file AnnocProc.java:

import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import.javaz.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. easy fix, bestie ๐Ÿ’…

๐Ÿฆ‹ rawtypes ๐Ÿฆ‹

Warns about unchecked operations on raw types. This 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. iconic behavior tbh.

๐Ÿ“ 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 is strongly recommended that all serializable classes explicitly declare serialVersionUID values, because the default process of computing serialVersionUID vales is highly sensitive to class details that can vary depending on compiler implementations, and as a result, 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. no cap, just declare it ๐Ÿ™ˆ

โญ static โญ

Warns about issues relating to the use of statics, 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. pick your fighter ๐Ÿ’€

๐Ÿ”ฅ try ๐Ÿ”ฅ

Warns about issues relating to use of try blocks, including try-with-resources statements. For example, a warning is generated for the following statement because the resource ac declared in the try block is not used:

try ( AutoCloseable ac = getResource() ) {    // do nothing}

๐Ÿ’œ 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

During type erasure, the types ArrayList<Number> and List<String> become ArrayList and List, respectively.

The ls command 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.

๐ŸŽ€ varargs ๐ŸŽ€

Warns about unsafe usages 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);
    }
  }
}
Note: 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 is a possibility of heap pollution. ๐Ÿ˜ญ it's giving chaos, honestly.

๐Ÿ—‚๏ธ COMMAND-LINE ARGUMENT FILES ๐Ÿ—‚๏ธ

okay so hear me out bestie โ€” sometimes your javac command gets SO long it's giving runway, and you're like "I cannot type all this every time." Enter argument files โœจ You can pass one or more files that contain arguments to the javac command (with one exception: not -J options, we'll get to why ๐Ÿ’…). This means you can literally create javac commands of any length on any operating system. Slay.

An argument file can hold javac options and source file names in any combination you want. Inside the file, the arguments can be separated by spaces or new line characters โ€” either vibes. And if a file name has embedded spaces, just wrap the whole file name in double quotation marks. Easy.

okay important stuff, don't skip this part ๐Ÿ™ˆ File names inside an argument file are relative to the current directory, not to the location of the argument file. Wild cards (*) are not allowed in these lists (so no *.java, bestie, sorry). Using the at sign (@) to recursively interpret files is not supported. And the -J options are not supported in argument files because they get passed to the launcher, which doesn't support argument files. That's the whole reason, no cap.

When you run the javac command, you pass in the path and name of each argument file with the at sign (@) leading character. When javac sees an argument starting with @, it expands the contents of that file into the argument list. Magic? No, just Unix ๐Ÿ’–

๐ŸŒธ Example 1 Single Argument File ๐ŸŒธ

You could use a single argument file named argfile to hold all javac arguments:

javac @argfile

This argument file could contain the contents of both files shown in Example 2. Iconic.

๐ŸŽ€ Example 2 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 โ€” none, zero, don't add them ๐Ÿซถ

Create a file named options that contains the following:

-d classes
-g
-sourcepath /java/pubs/ws/1.3/src/share/classes

Create a file named classes that contains the following:

MyClass1.java
MyClass2.java
MyClass3.java

Then, run the javac command as follows:

javac @options @classes

๐Ÿฆ‹ Example 3 Argument Files with Paths ๐Ÿฆ‹

The argument files can have paths, but any file names inside the files are relative to the current working directory (not path1 or path2) โ€” say it with me, current working directory:

javac @path1/options @path2/classes

๐Ÿ”ฎ ANNOTATION PROCESSING ๐Ÿ”ฎ

The javac command provides direct support for annotation processing, superseding the need for the separate annotation processing command, apt. Bye apt, you were cute but we've moved on ๐Ÿ’…

The API for annotation processors is defined in the javax.annotation.processing and javax.lang.model packages and subpackages.

โœจ HOW ANNOTATION PROCESSING WORKS โœจ

Unless annotation processing is disabled with the -proc:none option, the compiler searches for any annotation processors that are available. The search path can be specified with the -processorpath option. If 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 figure out 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 continues until no new source files are generated. It's giving "just one more round" energy and honestly we respect it ๐Ÿ˜ญ

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.

๐Ÿ’œ IMPLICITLY LOADED SOURCE FILES ๐Ÿ’œ

To compile a set of source files, the compiler might need to implicitly load additional source files. See Searching for Types. Such files are currently not subject to annotation processing. By default, the compiler gives a warning when annotation processing occurred and any implicitly loaded source files are compiled. The -implicit option provides a way to suppress the warning. You're welcome ๐ŸŽ€


๐Ÿ”Ž SEARCHING FOR TYPES ๐Ÿ”Ž

To compile a source file, the compiler often needs info about a type, but the type definition is not in the source files you specified on the command line. The compiler needs type information for every class or interface used, extended, or implemented in the source file. This includes classes and interfaces not explicitly mentioned in the source file, but that provide information through inheritance. iykyk ๐Ÿงš

For example, when you create a subclass java.applet.Applet, you are also using the ancestor classes of Applet: java.awt.Panel, java.awt.Container, java.awt.Component, and java.lang.Object. It's ancestors all the way down ๐Ÿ’€

When the compiler needs type information, it searches for a source file or class file that defines the type. The compiler searches for class files first in the bootstrap and extension classes, then in the user class path (which by default is the current directory). The user class path is defined by setting the CLASSPATH environment variable or by using the -classpath option.

If you set the -sourcepath option, then 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 the -extdirs options. See Cross-Compilation Options.

A successful type search may produce a class file, a source file, or both. If both are found, then you can use the -Xprefer option to instruct the compiler which to use. If newer is specified, then the compiler uses the newer of the two files. If source is specified, then the compiler uses the source file. The default is newer.

If a type search finds a source file for a required type โ€” either by itself, or as a result of the setting for the -Xprefer option โ€” then the compiler reads the source file to get the information it needs. By default the compiler also compiles the source file. You can use the -implicit option to specify the behavior. If none is specified, then no class files are generated for the source file. If class is specified, then class files are generated for the source file. Choose your fighter ๐Ÿซถ

The compiler might not discover the need for some type information until after annotation processing completes. When the type information is found in a source file and no -implicit option is specified, the compiler gives a warning that the file is being compiled without being subject to annotation processing. To disable the warning, either specify the file on the command line (so that it will be subject to annotation processing) or use the -implicit option to specify whether or not class files should be generated for such source files.


๐Ÿง‘โ€๐Ÿ’ป PROGRAMMATIC INTERFACE ๐Ÿง‘โ€๐Ÿ’ป

The javac command supports the new Java Compiler API defined by the classes and interfaces in the javax.tools package. Main character API energy, honestly ๐Ÿ‘‘

โญ EXAMPLE โญ

To compile as though providing command-line arguments, use the following syntax:

JavaCompiler javac = ToolProvider.getSystemJavaCompiler();

The example writes diagnostics to the standard output stream and returns the exit code that javac would give when called from the command line.

You can use other methods in the javax.tools.JavaCompiler interface to handle diagnostics, control where files are read from and written to, and more. The possibilities? Endless ๐Ÿ’–

๐ŸŒˆ OLD INTERFACE ๐ŸŒˆ

Note: This API is retained for backward compatibility only. All new code should use the newer Java Compiler API. No cap, it's literally in the note.

The com.sun.tools.javac.Main class provides two static methods to call the compiler from a program:

public static int compile(String[] args);
public static int compile(String[] args, PrintWriter out);

The args parameter represents any of the command-line arguments that would typically be passed to the compiler.

The out parameter indicates where the compiler diagnostic output is directed.

The return value is equivalent to the exit value from javac.

Note: All other classes and methods found in a package with names that start with com.sun.tools.javac (subpackages of com.sun.tools.javac) are strictly internal and subject to change at any time. So don't go building your whole personality on them, bestie ๐Ÿ˜ญ๐Ÿ’€

โœจ EXAMPLES โœจ

Okay bestie, this is the part where it all comes together โ€” real files, real commands, real "wait, it actually worked?!" moments. Let's go ๐Ÿ’…

๐ŸŒธ Example 1 Compile a Simple Program

This one shows you how to compile the Hello.java source file that lives in the greetings directory. The class defined in Hello.java is called greetings.Hello. The greetings directory is the package directory for both the source file and the class file, and it sits underneath the current directory. That's what makes it possible to just use the default user class path โ€” no extra setup, no drama. It also means you don't have to specify a separate destination directory with the -d option. Iconic behavior honestly โœจ

The source code in Hello.java:

package greetings;
public class Hello {
    public static void main(String[] args) {
        for (int i=0; i < args.length; i++) {
            System.out.println("Hello " + args[i]);
        }
    }
}

Compile greetings.Hello:

javac greetings/Hello.java

Run greetings.Hello:

java greetings.Hello World Universe Everyone
Hello World
Hello Universe
Hello Everyone

Look at that output. She ate and left no crumbs ๐Ÿ“


๐Ÿฆ‹ Example 2 Compile Multiple Source Files

This example compiles the Aloha.java, GutenTag.java, Hello.java, and Hi.java source files in the greetings package.

% javac greetings/*.java
% ls greetings
Aloha.class         GutenTag.class      Hello.class         Hi.class
Aloha.java          GutenTag.java       Hello.java          Hi.java

One wildcard, four classes compiled. The way that * just works ๐Ÿ˜ญ๐Ÿ’–


๐ŸŽ€ Example 3 Specify a User Class Path

So after changing one of the source files in the previous example, you recompile it:

pwd
/examples
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 are in, then add the examples directory to the user class path by setting CLASSPATH. This example uses the -classpath option.

javac -classpath /examples /examples/greetings/Hi.java

And if you change greetings.Hi to use a banner utility, then that utility also needs to be accessible through the user class path. Everything's connected, iykyk ๐Ÿงš

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.

java -classpath /examples:/lib/Banners.jar greetings.Hi

๐Ÿ‘‘ Example 4 Separate Source Files and Class Files

The following example uses javac to compile code that runs on JVM 1.7.

javac -source 1.7 -target 1.7 -bootclasspath jdk1.7.0/lib/rt.jar \
-extdirs "" OldCode.java

The -source 1.7 option specifies that release 1.7 (or 7) of the Java programming language be used to compile OldCode.java. The option -target 1.7 option ensures that the generated class files are compatible with JVM 1.7. Note that in most cases, the value of the -target option is the value of the -source option; in this example, you can omit the -target option. Convenient? Absolutely. But read on ๐Ÿ‘€

You must specify the -bootclasspath option to specify the correct version of the bootstrap classes (the rt.jar library). If not, then the compiler generates a warning:

javac -source 1.7 OldCode.java
warning: [options] bootstrap class path not set in conjunction with
-source 1.7
๐Ÿšจ And here's the part that actually matters, bestie: if you do not specify the correct version of bootstrap classes, then the compiler uses the old language rules (in this example, it uses version 1.7 of the Java programming language) combined with the new bootstrap classes, which can result in class files that do not work on the older platform (in this case, Java SE 7) because reference to nonexistent methods can get included. Literally a disaster waiting to happen ๐Ÿ’€

๐ŸŒˆ Example 5 Cross Compile

This example uses javac to compile code that runs on JVM 1.7.

javac -source 1.7 -target 1.7 -bootclasspath jdk1.7.0/lib/rt.jar \
            -extdirs "" OldCode.java

The -source 1.7 option specifies that release 1.7 (or 7) of the Java programming language to be used to compile OldCode.java. The -target 1.7 option ensures that the generated class files are compatible with JVM 1.7.

Same deal as before โ€” you must specify the -bootclasspath option to specify the correct version of the bootstrap classes (the rt.jar library). If not, then the compiler generates a warning:

javac -source 1.7 OldCode.java
warning: [options] bootstrap class path not set in conjunction with -source 1.7
๐Ÿ’€ If you do not specify the correct version of bootstrap classes, then the compiler uses the old language rules combined with the new bootstrap classes. This combination can result in class files that do not work on the older platform (in this case, Java SE 7) because reference to nonexistent methods can get included. In this example, the compiler uses release 1.7 of the Java programming language. Fr fr, do not skip the boot class path ๐ŸŒธ

๐Ÿ’œ SEE ALSO ๐Ÿ’œ

(yes, jdb(1) is listed twice โ€” that's how the page does it, and we respect the lore ๐Ÿ‘‘)


And that's the whole page, bestie โ€” you made it to the end ๐Ÿซถ This one's from JDK 8, dated 03 March 2015, the javac(1) page, and it's a whole journey. Go forth and compile something iconic โœจ๐Ÿ’…๐ŸŽ€

๐Ÿ“ฆ where this page comes from
  • centos-stream 9: java-11-openjdk-devel-fastdebug 1:11.0.20.1.1-2.el9 ยท ASL 1.1 and ASL 2.0 and BSD and BSD with advertising and GPL+ and GPLv2 and GPLv2 with exceptions and IJG and LGPLv2+ and MIT and MPLv2.0 and Public Domain and W3C and zlib and ISC and FTL and RSA
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms