JDK User Manual

Java Compiler Usage Guide

Basic javac Usage

javac is Java's compiler, responsible for compiling Java source code into bytecode files. Basic usage is very simple: javac HelloWorld.java. This will generate a HelloWorld.class file, which can then be run on JVM.

In actual development projects, more compilation options are usually needed. Common options include: -d specifies the compilation output directory, for example, javac -d out HelloWorld.java will put compiled results in the out directory; -classpath (or -cp) specifies the class search path for referencing external classes during compilation; -source specifies the Java version of the source code; -target specifies the Java version of the generated bytecode.

For large projects, build tools like Maven or Gradle are typically used to manage the compilation process. These tools automatically handle dependencies and compilation options.

Compiling Multiple Files

If your project contains multiple Java source files, you can compile an entire directory at once. For example: javac -d out src/*.java will compile all Java files in the src directory.

More complex project structures may require using the -sourcepath option to specify the source code search path, allowing the compiler to find dependent classes. For example: javac -d out -sourcepath src src/Main.java.

Handling Compilation Errors

If errors occur during compilation, javac outputs detailed error information including the file, line number, and specific cause. Common compilation errors include: syntax errors (missing semicolons, mismatched brackets, etc.), type errors (incompatible types, non-existent methods, etc.), and access permission errors (attempting to access private members, etc.).

Understanding these error messages is crucial for quickly locating and resolving issues. The compiler reports as many errors as possible; sometimes fixing the first error will make subsequent errors disappear.

Running Java Programs Guide

Basic java Command Usage

Use the java command to run compiled Java programs. Basic syntax is: java HelloWorld. Note that the .class extension is not needed here. JVM will automatically find Hello.class in the current directory and CLASSPATH.

If the class is in a package, use the fully qualified name. For example: java com.example.HelloWorld.

Classpath (CLASSPATH)

Classpath tells JVM where to find class files. It can be specified using the -classpath or -cp option. For example: java -cp out:lib/* com.example.HelloWorld. On Windows, the path separator is semicolon (;); on Linux and macOS, it's colon (:).

If classpath is not specified, JVM will use the current directory and paths specified in the CLASSPATH environment variable.

JVM Options

JVM provides numerous startup options for controlling runtime behavior. Common options include: -Xms specifies the initial heap size, like -Xms256m sets initial heap to 256MB; -Xmx specifies the maximum heap size, like -Xmx2g sets maximum heap to 2GB; -XX:+UseG1GC uses the G1 garbage collector.

On JDK 9 and later, you can use the --add-opens option to open module internal access, which is useful when running libraries that need to access JDK internal APIs.

JDK Tools Usage Guide

jar Archive Tool

The jar tool is used for creating and managing Java archive files (.jar files). .jar files are actually ZIP-formatted compressed packages containing compiled .class files and some metadata.

Basic command to create a jar file: jar cf myapp.jar -C out . This creates myapp.jar from the contents of the out directory. Use the tf parameter to view jar file contents: jar tf myapp.jar. Use xf to extract: jar xf myapp.jar.

When creating an executable jar file, you need to specify the main class in the MANIFEST.MF file. You can add a custom MANIFEST.MF using the m parameter: jar cfm myapp.jar MANIFEST.MF -C out .

javadoc Documentation Generation

The javadoc tool generates HTML-format API documentation from comments in Java source code. The standard Java library documentation is generated this way.

Basic usage: javadoc -d doc src/*.java. This generates documentation for all Java files in the src directory and puts it in the doc directory.

When writing code, using specific comment formats can add documentation for classes, methods, and fields. Common comment tags include: @author author, @param parameter, @return return value, @throws exception, etc.

jdb Debugger

jdb is Java's command-line debugger, providing basic debugging functionality. Start debugging: jdb MyClass. Set breakpoints: stop in MyClass.method. View breakpoints: clear. Run program: run. Continue execution: cont. Step through: step or next. View variables: print varname. List source code: list.

Although jdb is not as powerful as graphical debuggers, it can be used in environments without IDEs or for remote debugging on servers.

JVM Performance Tuning

Choosing a Garbage Collector

JDK provides multiple garbage collectors, each with different characteristics and applicable scenarios:

Serial GC: Single-threaded collector, suitable for small applications and client applications. Enable with -XX:+UseSerialGC.

Parallel GC (Throughput GC): Multi-threaded collector, suitable for applications pursuing high throughput. Enable with -XX:+UseParallelGC.

CMS GC: Concurrent Mark Sweep collector, pursuing low pause times. Enable with -XX:+UseConcMarkSweepGC (Deprecated in JDK 14).

G1 GC: Partitioning garbage collector, suitable for large memory applications, and became the default option in JDK 9 and later. Using default settings or -XX:+UseG1GC is recommended.

ZGC: Low-latency garbage collector, supports TB-level heap memory, pause times not exceeding 10ms. Enable with -XX:+UseZGC (JDK 15+).

Shenandoah: Another low-latency garbage collector, pause times independent of heap size. Enable with -XX:+UseShenandoahGC.

Memory Configuration

Reasonably configuring heap memory size is essential for application performance. Common configuration options:

-Xms: Initial heap size, e.g., -Xms2g. -Xmx: Maximum heap size, e.g., -Xmx4g. -Xmn: Young generation size, e.g., -Xmn1g. -XX:MetaspaceSize: Initial metaspace size. -XX:MaxMetaspaceSize: Maximum metaspace size.

It's recommended to set -Xms and -Xmx to the same value to avoid overhead from runtime heap adjustments.

Performance Monitoring Tools

JDK provides rich performance monitoring and diagnostic tools:

jps: Displays list of Java processes, basic usage jps -l. jstat: Displays JVM statistics, e.g., garbage collection statistics: jstat -gcutil pid 1000. jstack: Prints thread stack information, used for diagnosing deadlocks: jstack pid. jmap: Displays heap memory information, e.g., generating heap dump: jmap -dump:format=b,file=heap.bin pid. jcmd: Multi-function diagnostic tool, can execute various diagnostic commands: jcmd pid GC.heap_info.

JConsole and VisualVM: Graphical monitoring and diagnostic tools, can monitor memory, threads, CPU usage, etc.

Module System

Module Overview

Starting from JDK 9, Java introduced the module system (Project Jigsaw), dividing JDK itself and applications into modules. Each module has clear dependencies, providing better encapsulation and maintainability.

JDK itself is divided into multiple modules like java.base, java.sql, java.xml. Applications can create their own modules, declaring module name, dependencies, and exports through module-info.java files.

JDK provides multiple command-line options related to modules:

--module-path (or -p): Specifies module path, similar to classpath but for modules. --add-modules: Adds modules to the default module set. --add-exports: Opens specified module packages for other modules to access. --add-opens: Opens specified module packages for reflection access.

These options are very important in certain situations, such as when using reflection to access JDK internal APIs or when using libraries not compatible with modularization.

Common Configuration Examples

Development Environment Configuration

For daily development environments, recommended configurations include: sufficient heap memory (-Xmx2g or higher), using G1 garbage collector (default), enabling class data sharing (-Xshare:classes) to speed up startup. If using IDE, you can set these options directly in the IDE's run configuration.

Production Environment Configuration

Production environment configuration needs to be adjusted based on the application's specific situation. Basic principles include: setting heap size according to application memory needs, usually reserving 25-30% of memory for the OS and other processes; choosing an appropriate garbage collector, G1 is usually a good choice; for applications pursuing low latency, consider using ZGC or Shenandoah.

It's recommended to enable GC logging in production environments, recording detailed garbage collection information for problem analysis and performance tuning. GC logging configuration example: -Xlog:gc*:file=gc.log:time,uptime,level,tags:filecount=5,filesize=10M.

Docker Container Configuration

When running Java applications in container environments, pay attention to JVM's memory awareness. JDK 10+ versions are aware of container memory limits by default, but manual configuration may be needed in earlier versions.

Recommended configuration: set correct maximum heap value (-XX:MaxRAMPercentage=75.0), ensuring JVM doesn't use more than 75% of container available memory; use -XX:+UseContainerSupport (enabled by default) to let JVM be aware of container resource limits.

For cloud-native applications, consider using GraalVM Native Image to compile applications into native executables, which can significantly reduce startup time and memory usage.

Version-Specific Usage Differences

JDK 8

JDK 8 is the last version with completely free Oracle JDK for commercial use. Key features include lambda expressions, streams API, and new date/time API. Installation is relatively simple, using the traditional installer. Note that JAVA_HOME should point to the JDK directory (not JRE). Some commands and tools may behave differently in newer versions.

JDK 11

JDK 11 marked the beginning of Java's paid features. Key features include local variable type inference (var keyword), new HTTP client API, and ZGC (experimental). The JRE is no longer provided as a separate download; only JDK is available. The java command can run single-file source-code programs directly without compilation.

JDK 17

JDK 17 is the last free Oracle JDK version under NFTC. Key features include sealed classes, text blocks, and switch expressions. Installation and usage are similar to JDK 11. The RandomGenerator interface provides new random number generation capabilities. Foreign memory access API entered incubation phase.

JDK 21

JDK 21 introduces significant features including Virtual Threads (stable), pattern matching for switch (stable), and records (stable). Virtual Threads require different concurrency programming approaches. The heap settings may need adjustment for applications using virtual threads. Performance tuning should consider virtual thread characteristics.

JDK 25

JDK 25 is the latest version with the newest language features and performance improvements. Features may still be in preview or experimental status. Not recommended for production environments requiring long-term support. The configuration and usage are similar to JDK 21, but with more new features that may require additional learning.