Executing Java Programs
Java Program Execution Workflow
graph TD
A[Source Code .java] --> B[Compile with javac]
B --> C[Bytecode .class]
C --> D[Run with java command]
Creating a Java Source File
## Create a directory for Java projects
mkdir ~/JavaProjects
cd ~/JavaProjects
## Create a sample Java file
nano HelloWorld.java
Sample Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Welcome to LabEx Java Tutorial!");
}
}
Compilation Process
## Compile the Java source file
javac HelloWorld.java
## This creates HelloWorld.class bytecode file
ls
Running Java Programs
## Execute the compiled Java program
java HelloWorld
Execution Methods
Method |
Command |
Description |
Direct Execution |
java ClassName |
Run compiled class |
With Package |
java package.ClassName |
Run packaged classes |
With Arguments |
java ClassName arg1 arg2 |
Pass command-line arguments |
Advanced Execution Techniques
Compiling Multiple Files
## Compile all Java files in current directory
javac *.java
Running with Classpath
## Add external libraries or custom classpaths
java -cp ./lib:. MainClass
Handling Compilation Errors
Common error types:
- Syntax Errors
- Compilation Errors
- Runtime Errors
Error Checking
## Detailed compilation error information
javac -verbose HelloWorld.java
Best Practices
- Use meaningful class and file names
- Handle exceptions
- Organize code in packages
- Use consistent indentation
LabEx Tip
LabEx recommends practicing Java execution in a controlled, interactive environment to build confidence and skills.