1.4 Compiling, Running, and Package Management

Key Takeaways

  • Compiling source code requires javac SourceFile.java (specifying the complete .java file extension), which parses syntax and emits a .class bytecode file for each class declared in the source.
  • Launching an application requires java ClassName (supplying the fully qualified class name without any file extension); appending .class causes a runtime class loading error.
  • Classes declared in named packages must be compiled and executed relative to the package root directory using their fully qualified class names (e.g., java com.example.app.MainApp).
  • Command-line arguments supplied after the class name are passed to main as a zero-indexed String[] array; elements are always strings and must be parsed explicitly for numerical operations.
  • The classpath (-cp or -classpath) defines the search paths for user classes and external archive libraries (.jar), using a colon (:) separator on Unix/macOS and a semicolon (;) on Windows.
Last updated: September 2026

1.4 Compiling, Running, and Package Management

[!NOTE] Exam Focus: In the 1Z0-811 examination, practical understanding of command-line tool syntax is tested thoroughly. Candidates must know the exact syntax of javac versus java, understand why the .class extension must never be passed to the java launcher, understand how command-line arguments are mapped to args[0] and args[1], and know how to configure the classpath (-cp).

While modern software development commonly utilizes Integrated Development Environments (IDEs) such as IntelliJ IDEA, Eclipse, or NetBeans, the Oracle Certified Foundations Associate exam tests candidate mastery of core JDK command-line tools. Grasping how the Java compiler and application launcher operate directly from the operating system shell ensures a deep understanding of Java's underlying build and execution mechanics.


The JDK Command-Line Toolset

When the Java Development Kit (JDK) is installed and its bin directory is added to the system's PATH environment variable, developers have access to a suite of command-line utilities:

CommandUtility NameInputOutputPrimary Role
javacJava CompilerSource code files (.java)Bytecode files (.class)Compiles human-readable source code into JVM bytecode
javaJava Application LauncherCompiled class name (no extension)Application executionStarts JVM, loads bytecode, and invokes main method
javadocDocumentation GeneratorSource code files (.java)HTML documentationGenerates API documentation from Javadoc comments
jarJava Archive Utility.class files, resource assets.jar archive fileCompresses and packages compiled applications into a ZIP archive
jdbJava DebuggerCompiled bytecode and sourceInteractive debug sessionInspects breakpoints, call stacks, and thread variables

Compiling Source Code with javac

The javac command invokes the Java compiler. Its primary responsibility is to parse source code, enforce language syntax rules, perform type checking, and generate .class bytecode files.

Command Syntax

javac [options] [sourcefiles]

For example, to compile a simple application named GreetingApp.java:

javac GreetingApp.java

[!IMPORTANT] File Extension Requirement: When invoking javac, you must supply the complete file name, including the .java extension. If you omit the extension (e.g., typing javac GreetingApp), the compiler will produce an error: error: Class names, 'GreetingApp', are only accepted if annotation processing is explicitly requested.

Compilation Produces One .class File per Class Declaration

A common exam question explores what happens when a single .java file contains multiple class definitions:

// Saved in file: Company.java
public class Company {
    // ...
}
class Employee {
    // ...
}
class Department {
    // ...
}

When you compile Company.java using javac Company.java, the compiler produces three separate bytecode files on disk:

  1. Company.class
  2. Employee.class
  3. Department.class

The compiler produces a distinct .class file for every single class or interface defined in the source file.

Essential javac Command Options

  • -d <directory>: Specifies the destination directory where generated .class files should be placed. If the source file includes a package declaration, the -d option automatically creates the corresponding directory hierarchy:
    javac -d ./bin src/com/oracle/exam/MainApp.java
    
    This command compiles MainApp.java and places MainApp.class inside the directory ./bin/com/oracle/exam/.
  • -cp or -classpath <path>: Specifies where the compiler should search for dependent class files and external libraries needed to compile the source code.
  • -version: Displays the compiler version (e.g., javac 1.8.0_381).

Running Applications with the java Launcher

Once source code has been compiled into .class bytecode, the application is executed using the java command (the Java application launcher). The launcher starts the Java Virtual Machine, loads the specified class, verifies its bytecode, and calls its public static void main(String[] args) method.

Command Syntax

java [options] classname [args...]

To execute the compiled class GreetingApp:

java GreetingApp

[!WARNING] The .class Extension Trap: You must provide the class name, NEVER the file name with .class! If you execute:

java GreetingApp.class

The JVM launcher will interpret GreetingApp.class as a class named class residing inside a package named GreetingApp. The JVM will fail with the error: Error: Could not find or load main class GreetingApp.class.

Running Packaged Classes

If a class declares a package, it must be executed using its Fully Qualified Class Name (FQCN) from the root of the package directory:

// File: src/com/example/reports/DailyReport.java
package com.example.reports;

public class DailyReport {
    public static void main(String[] args) {
        System.out.println("Generating Report...");
    }
}

If compiled into the bin directory, the command must be executed from bin (the directory containing com):

cd bin
java com.example.reports.DailyReport

If you navigate inside bin/com/example/reports/ and attempt to run java DailyReport, the JVM will throw a NoClassDefFoundError because the package name (com.example.reports) does not match your current relative directory path.

Loading diagram...
JDK Command-Line Build and Execution Pipeline

Working with Command-Line Arguments

When launching an application, developers can pass information into the program by providing arguments on the command line following the class name:

java WelcomeApp Alice 42 true

The JVM captures every argument following the class name, separates them by whitespace, and stores them in a String[] array passed into the main method's args parameter.

Command-Line Argument Mechanics

  1. Zero-Based Indexing: Elements are accessed starting at index 0:
    • args[0] stores "Alice"
    • args[1] stores "42"
    • args[2] stores "true"
    • args.length evaluates to 3
  2. Arguments Are Always Strings: Regardless of whether you pass text, numbers, or booleans, the JVM always provides them as java.lang.String literals. To perform numeric calculations, arguments must be explicitly parsed using wrapper class conversion methods:
    int age = Integer.parseInt(args[1]); // Converts String "42" to primitive int 42
    boolean flag = Boolean.parseBoolean(args[2]); // Converts "true" to boolean true
    
  3. Difference from C and C++: In C and C++, argv[0] contains the name of the executable itself. In Java, the class name is NOT included in args. args[0] always holds the very first argument provided after the class name.
  4. Handling Arguments with Spaces: If an argument contains whitespace, it must be enclosed in quotation marks:
    java Greeter "San Francisco" "New York"
    
    Here, args[0] is "San Francisco" and args[1] is "New York" (args.length is 2).

Bounds Checking and ArrayIndexOutOfBoundsException

If a program attempts to access an index that does not exist in args, the JVM throws an ArrayIndexOutOfBoundsException at runtime:

public class Greeter {
    public static void main(String[] args) {
        // Safe coding practice: verify array length before accessing elements!
        if (args.length > 0) {
            System.out.println("Hello, " + args[0]);
        } else {
            System.out.println("Hello, Guest!");
        }
    }
}

If an inexperienced developer writes System.out.println(args[0]); without checking args.length, and a user executes java Greeter with no arguments, args will be an empty array (args.length == 0), causing a fatal crash: java.lang.ArrayIndexOutOfBoundsException: 0.


The Classpath Mechanism (-cp and -classpath)

The classpath is the search path that the Java compiler (javac) and runtime launcher (java) use to locate .class bytecode files and archive packages (.jar files). By default, if no classpath is specified, the JVM searches only the current working directory (.).

Setting the Classpath via Command-Line Flags

The classpath can be configured using either -cp or -classpath:

java -cp ./build/classes:./libs/mysql.jar com.example.DatabaseApp

Operating System Path Separators

A key detail for cross-platform execution is the path separator character used to delimit multiple directories or JAR files in the classpath argument:

Operating SystemPath SeparatorExample Classpath Syntax
Unix / Linux / macOSColon (:)java -cp ./bin:./lib/util.jar com.app.Main
Microsoft WindowsSemicolon (;)java -cp .\bin;.\lib\util.jar com.app.Main

Diagnosing and Resolving Common Errors

The 1Z0-811 exam requires candidates to inspect code and command-line scenarios to identify whether an error occurs at compile time or runtime, and determine the exact root cause.

1. Compile-Time Errors (Emitted by javac)

Compile-time errors prevent bytecode generation. The .class file is never created.

  • error: cannot find symbol: The compiler cannot locate a referenced variable, method, or class. Common causes include misspelled variable names, referencing variables out of scope, or forgetting to import an external class (import java.util.Scanner;).
  • error: class X is public, should be declared in a file named X.java: The name of the public class does not match the source file name exactly, including letter case.
  • error: Class names, '...', are only accepted if annotation processing is explicitly requested: The developer forgot the .java extension when invoking javac (e.g., javac MyApp instead of javac MyApp.java).
  • error: unreachable statement: Code is placed after an unconditional return, break, continue, or throw statement.

2. Runtime Errors (Emitted by the java Launcher)

Runtime errors occur while the application is executing inside the JVM.

  • Error: Could not find or load main class X: The JVM launcher cannot locate the specified class. Common causes include appending .class to the command line (java App.class), omitting package prefixes when executing packaged classes, or failing to include the class's directory in the -cp classpath.
  • Error: Main method not found in class X, please define the main method as: public static void main(String[] args): The class exists and was loaded, but it does not contain a method matching the exact entry point signature. Common causes include omitting static, changing the return type from void to int, or misnaming the parameter type.
  • java.lang.NoClassDefFoundError: The class was present when the code was compiled, but cannot be located at runtime when the JVM attempts to instantiate it.
  • java.lang.ArrayIndexOutOfBoundsException: The program attempted to access an element of an array with an index that is negative or greater than or equal to array.length (frequently occurring when reading args[0] without verifying args.length > 0).
Diagnostic Error MessagePhaseRoot CauseCorrective Resolution
cannot find symbolCompile-TimeTypo, missing import, or variable referenced outside its lexical scopeVerify spelling, scope, and ensure package import statement exists
class X is public, should be declared...Compile-TimeSource filename does not match the public class name exactlyRename file to match public class name, preserving exact letter case
Could not find or load main classRuntimeAppended .class extension or omitted package path from commandRemove .class extension; run from package root with full package prefix
Main method not found in classRuntimeMissing static, wrong return type, or wrong parameter list in mainDeclare signature exactly: public static void main(String[] args)
ArrayIndexOutOfBoundsExceptionRuntimeAccessing command-line argument when user passed insufficient inputsAdd conditional guard checking args.length > requiredIndex before access
Test Your Knowledge

A developer compiles a file containing public class InvoiceApp inside package com.finance using the command javac -d ./bin src/com/finance/InvoiceApp.java. What is the correct terminal command to run this application from the project root directory?

A
B
C
D
Test Your Knowledge

A developer executes the following command in terminal: java OrderProcessor 100 0.08 "Priority Shipping" Inside the main method of OrderProcessor, what are the values of args.length and args[2]?

A
B
C
D
Test Your Knowledge

A programmer types the following command in their terminal prompt to execute a newly compiled standalone application: java PayrollReport.class What is the outcome of running this command?

A
B
C
D