Program Execution
Java Program Execution Basics
Java program execution involves running compiled bytecode through the Java Virtual Machine (JVM), which provides a runtime environment for Java applications.
Execution Workflow
graph TD
A[Compiled .class File] --> B[Java Virtual Machine]
B --> C[Bytecode Verification]
C --> D[Interpretation/Compilation]
D --> E[Program Output]
Running Java Programs
On Ubuntu 22.04, you can execute Java programs using the java
command:
## Basic execution
java ClassName
## Run with classpath
java -cp ./bin ClassName
## Run with specific JVM options
java -Xmx512m ClassName
Execution Methods
Method |
Description |
Example |
Direct Execution |
Run compiled class directly |
java HelloWorld |
Classpath Execution |
Run with multiple class files |
java -cp ./lib:. MainClass |
JAR File Execution |
Run packaged applications |
java -jar myapp.jar |
Practical Execution Example
// UserGreeter.java
public class UserGreeter {
public static void main(String[] args) {
String username = args.length > 0 ? args[0] : "LabEx User";
System.out.println("Welcome, " + username + "!");
}
}
Compile and run the program:
## Compile the source code
javac UserGreeter.java
## Run without arguments
java UserGreeter
## Run with a custom username
java UserGreeter "John Doe"
Command-Line Arguments
Java allows passing arguments to the main
method:
public static void main(String[] args) {
for (String arg : args) {
System.out.println("Argument: " + arg);
}
}
Option |
Purpose |
Example |
-Xmx |
Set maximum heap size |
java -Xmx512m MyApp |
-Xms |
Set initial heap size |
java -Xms256m MyApp |
-verbose:gc |
Print garbage collection details |
java -verbose:gc MyApp |
Common Execution Challenges
- ClassNotFoundException
- NoSuchMethodError
- OutOfMemoryError
- Incompatible Java versions
LabEx Execution Tips
When using LabEx for Java programming:
- Ensure consistent JDK versions
- Use appropriate JVM settings
- Practice error handling
- Optimize memory usage
Advanced Execution Techniques
## Remote debugging
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 MyApp
## JVM profiling
java -XX:+PrintCompilation MyApp