Compiling and Running Java Programs via Command Line
Java development involves using command-line tools to compile and execute programs. The primary commands are javac for compilation and java for execution.
Compiling Java Source Code
Use the javac command too compile Java source files, typically with a .java extension. The basic syntax is:
javac [options] [source_file]
- Options:
-d: Specifies the output directory for compiled class files; defaults to the current directory.-g: Generates debugging information for use by debuggers.-classpath: Sets the classpath to locate dependent class files during compilation.
- Source File: The path to the Java source file to be compiled.
Example:
javac -d . GreetingProgram.java
This compiles GreetingProgram.java and places the resulting .class file in the current directory.
Executing Compiled Java Programs
After compilation, run the program with the java command. The basic syntax is:
java [options] [class_name]
- Options:
-cpor-classpath: Specifies the classpath to find the class files at runtime.
- Class Name: The name of the class to execute, without the
.classextension.
Example:
java GreetingProgram
This executes the GreetingProgram.class file located in the current directory.
Complete Example of Compilation and Execution
Consider a Java source file named GreetingProgram.java with the following content:
public class GreetingProgram {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Steps:
-
Compile:
javac GreetingProgram.javaThis generates a
GreetingProgram.classfile. -
Execute:
java GreetingProgramThis runs the compiled program, outputting
Hello, World!.
Handling Multiple Source Files
For programs with multiple interdependent source files, ensure all related .class files are in the same directory or specify the correct classpath using -cp or -classpath.
Example:
javac -d . Application.java Helper.java
java Application
Managing Package Structuers
If Java source files use package structures (e.g., in different directories), correctly specify the classpath during compilation and execution.
Example:
javac -d . com/myapp/Application.java
java -cp . com.myapp.Application