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.
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
javacversusjava, understand why the.classextension must never be passed to thejavalauncher, understand how command-line arguments are mapped toargs[0]andargs[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:
| Command | Utility Name | Input | Output | Primary Role |
|---|---|---|---|---|
javac | Java Compiler | Source code files (.java) | Bytecode files (.class) | Compiles human-readable source code into JVM bytecode |
java | Java Application Launcher | Compiled class name (no extension) | Application execution | Starts JVM, loads bytecode, and invokes main method |
javadoc | Documentation Generator | Source code files (.java) | HTML documentation | Generates API documentation from Javadoc comments |
jar | Java Archive Utility | .class files, resource assets | .jar archive file | Compresses and packages compiled applications into a ZIP archive |
jdb | Java Debugger | Compiled bytecode and source | Interactive debug session | Inspects 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.javaextension. If you omit the extension (e.g., typingjavac 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:
Company.classEmployee.classDepartment.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.classfiles should be placed. If the source file includes apackagedeclaration, the-doption automatically creates the corresponding directory hierarchy:
This command compilesjavac -d ./bin src/com/oracle/exam/MainApp.javaMainApp.javaand placesMainApp.classinside the directory./bin/com/oracle/exam/.-cpor-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
.classExtension Trap: You must provide the class name, NEVER the file name with.class! If you execute:java GreetingApp.classThe JVM launcher will interpret
GreetingApp.classas a class namedclassresiding inside a package namedGreetingApp. 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.
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
- Zero-Based Indexing: Elements are accessed starting at index
0:args[0]stores"Alice"args[1]stores"42"args[2]stores"true"args.lengthevaluates to3
- Arguments Are Always Strings: Regardless of whether you pass text, numbers, or booleans, the JVM always provides them as
java.lang.Stringliterals. 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 - 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 inargs.args[0]always holds the very first argument provided after the class name. - Handling Arguments with Spaces: If an argument contains whitespace, it must be enclosed in quotation marks:
Here,java Greeter "San Francisco" "New York"args[0]is"San Francisco"andargs[1]is"New York"(args.lengthis2).
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 System | Path Separator | Example Classpath Syntax |
|---|---|---|
| Unix / Linux / macOS | Colon (:) | java -cp ./bin:./lib/util.jar com.app.Main |
| Microsoft Windows | Semicolon (;) | 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 thepublicclass 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.javaextension when invokingjavac(e.g.,javac MyAppinstead ofjavac MyApp.java).error: unreachable statement: Code is placed after an unconditionalreturn,break,continue, orthrowstatement.
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.classto the command line (java App.class), omitting package prefixes when executing packaged classes, or failing to include the class's directory in the-cpclasspath.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 omittingstatic, changing the return type fromvoidtoint, 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 toarray.length(frequently occurring when readingargs[0]without verifyingargs.length > 0).
| Diagnostic Error Message | Phase | Root Cause | Corrective Resolution |
|---|---|---|---|
cannot find symbol | Compile-Time | Typo, missing import, or variable referenced outside its lexical scope | Verify spelling, scope, and ensure package import statement exists |
class X is public, should be declared... | Compile-Time | Source filename does not match the public class name exactly | Rename file to match public class name, preserving exact letter case |
Could not find or load main class | Runtime | Appended .class extension or omitted package path from command | Remove .class extension; run from package root with full package prefix |
Main method not found in class | Runtime | Missing static, wrong return type, or wrong parameter list in main | Declare signature exactly: public static void main(String[] args) |
ArrayIndexOutOfBoundsException | Runtime | Accessing command-line argument when user passed insufficient inputs | Add conditional guard checking args.length > requiredIndex before access |
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 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 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?