Java command line switches let you control how the Java Virtual Machine (JVM) and Java applications behave at startup. They modify memory, logging, performance, and security settings without changing code. To use them, you must have the Java Development Kit (JDK) or Java Runtime Environment (JRE) installed and accessible from your system's PATH. The switches follow the `java` command, placed before the class name or JAR file.
What You'll Need
- A working installation of JDK 8 or newer (JRE 8+ works for running JARs but lacks tools like `jvisualvm`)
- Access to a terminal or command prompt (Command Prompt on Windows, Terminal on macOS/Linux)
- A compiled Java class or `.jar` file to run
- Basic familiarity with running Java from the command line (e.g., `java MyClass`)
Step-by-Step
- Verify your Java installation: Open your terminal and run `java -version`. If it returns version info (e.g., "openjdk version "11.0.2""), Java is installed and in your PATH. If not, download and install the latest LTS JDK from Oracle or Adoptium.
- Locate your target class or JAR: Ensure the `.class` file is compiled (e.g., `javac MyClass.java`) and in your current directory or classpath, or identify your `.jar` file path (e.g., `myapp.jar`).
- Basic syntax for switches: Command format is `java [switches] ClassName [arguments]` or `java [switches] -jar app.jar [arguments]`. Switches always start with a dash (`-`) and appear *before* the class/JAR name. For example: `java -Xmx512m MyClass`.
- Set memory limits: Use `-Xms` for initial heap size and `-Xmx` for maximum heap size. Example: `java -Xms256m -Xmx1024m -jar myapp.jar`. Values can use `k`/`K` (kilobytes), `m`/`M` (megabytes), or `g`/`G` (gigabytes). Never exceed your system’s available RAM.
- Enable or configure garbage collection logging: Add `-Xlog:gc*` for Java 9+ (or `-XX:+PrintGC` for Java 8). Example: `java -Xlog:gc:file=gc.log:time,uptime,level,tags -jar myapp.jar`. This logs GC events to `gc.log` for performance tuning.
- Set system properties: Use `-Dproperty=value` to pass configuration (e.g., `-Dserver.port=8080` for Spring Boot). Example: `java -Dlogging.level.root=INFO -jar myapp.jar`.
- Enable debug mode for remote debugging: Run with `-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005`. Then attach an IDE debugger to port 5005. Ensure firewall allows the port.
- Specify the main class explicitly (if needed): If the JAR lacks a `Main-Class` manifest entry, use `-cp` (class path) and name the class: `java -cp lib/*:classes com.example.Main` (Linux/macOS) or `java -cp "lib/*;classes" com.example.Main` (Windows).
- Control the JIT compiler: Use `-Xint` to run in interpreted-only mode (for debugging), `-Xcomp` to compile all methods at first use (rarely recommended), or `-XX:+UseG1GC` to force the G1 garbage collector.
- Test your setup: After adding switches, run the command and check for expected behavior: e.g., `gc.log` appears for GC logging, or the app starts with new memory limits (check logs or use `jstat -gc
`).
Common Mistakes
- Placing switches after the class/JAR: The JVM ignores switches that appear after `ClassName` or `-jar app.jar`. Example: `java -jar app.jar -Xmx1g` fails; use `java -Xmx1g -jar app.jar`.
- Using invalid memory units: `-Xmx2G` works, but `-Xmx2gb` or `-Xmx2048` (without unit) may cause errors or misinterpretation. Stick to `m` or `g` in lowercase.
- Overriding critical switches unintentionally: `-Xmx1g -Xms2g` sets max heap smaller than initial heap, which fails at startup. Always ensure `-Xms ≤ -Xmx`.
- Confusing `-D` with environment variables: `-Dmykey=value` sets a Java system property, *not* an OS environment variable. Java processes won’t see OS env vars unless passed explicitly.
- Ignoring platform-specific path separators: Use `:` on Linux/macOS for `-cp`, but `;` on Windows. Mixing them (e.g., `-cp lib/*:classes` on Windows) causes `ClassNotFoundException`.
- Using deprecated flags in newer Java versions: `-XX:+UseConcMarkSweepGC` is obsolete in Java 14+. Use `-XX:+UseG1GC` instead. Check `java -XX:+PrintFlagsFinal` for valid flags per version.
Tips
- Group memory and GC switches together for readability: `java -Xms512m -Xmx2g -Xlog:gc* -jar app.jar`
- Use `-XX:+PrintCommandLineFlags` to see which switches were auto-set by the JVM (e.g., heap size, GC type).
- Escape special characters in `-D` values: For spaces or symbols, wrap in quotes: `-Dname="my app"` on Windows, or use `-Dname=my\ app` on Linux/macOS.
- Debug startup issues with `-verbose:class`: This prints every class loaded and its source JAR, helping diagnose missing dependencies.
- Test switches in a dev environment first: Production memory/GC changes can cause instability if misconfigured. Always validate with load tests.
- For Spring Boot apps, use `SPRING_PROFILES_ACTIVE` as an environment variable *or* `-Dspring.profiles.active=prod` as a switch.
Troubleshooting
If your Java command fails or behaves unexpectedly, follow these checks:
- Verify syntax Look for typos like `-Xmx1g` vs `-Xmx1G`.
- Check for out-of-memory errors: If you see `java.lang.OutOfMemoryError: Java heap space`, increase `-Xmx` (e.g., `-Xmx2g`). If `Metaspace` errors occur, add `-XX:MaxMetaspaceSize=256m`.
- Confirm classpath correctness: Use `-verbose:class` to see where classes load from. If a class isn’t found, ensure `-cp` includes all JARs and directories, and paths use the correct separator (`:` or `;`).
- Test with minimal switches: Run `java -jar app.jar` without switches to confirm the app works baseline. Add switches incrementally to isolate the problem.
- Check Java version compatibility: Run `java -version`. Flags like `-XX:+UseG1GC` exist in Java 8+, but `-XX:+UseZGC` requires Java 11+ and may need `-XX:+UnlockExperimentalVMOptions` first.
- Review logs and output: For GC issues, check `gc.log`. For startup hangs, use `-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/heap.hprof` to capture a dump for analysis.
Frequently Asked Questions
Can I use Java command line switches with any Java application?
Yes, but only if the application runs on the JVM. Switches affect the JVM and all code it runs. However, some frameworks (e.g., Tomcat) wrap the `java` command and may require switches via environment variables like `JAVA_OPTS` instead of direct CLI use.
Do switches like -Xmx work in Docker containers?
Yes, but older JVMs (pre-Java 10) ignore container memory limits, potentially causing OOM kills. Use `-XX:+UseContainerSupport` (enabled by default in Java 10+) and `-XX:MaxRAMPercentage=75.0` to let the JVM adapt to container limits.
What’s the difference between -XX: and -X: switches?
`-X` options are non-standard but widely supported (e.g., `-Xmx`, `-Xms`). `-XX:` options are advanced, experimental, or version-specific. `-XX:` flags may change or disappear between releases, while `-X` flags are more stable.
How do I list all available switches for my Java version?
Run `java -X` for common `-X` switches. For `-XX:` flags, use `java -XX:+PrintFlagsFinal | less` (Linux/macOS) or `java -XX:+PrintFlagsFinal | findstr /i "heap gc"` (Windows) to filter.
Why does my app ignore the -Dflag I set?
First, confirm the flag name matches what the app expects (e.g., `server.port` not `port`). Second, ensure the switch appears *before* `-jar` or the class name. Third, some frameworks override `-D` values with environment variables or config files—check their documentation.
Can I combine multiple switches in one command?
Yes. All standard switches can be combined: `java -Xms512m -Xmx2g -Denv=prod -Xlog:gc* -jar app.jar`. Order usually doesn’t matter, but keep them grouped for readability and before the class/JAR.