Compiling and Running Java Code
Once you have the Java Development Kit (JDK) installed, you can start writing and compiling Java code. Here's how to compile and run a simple Java program on an Ubuntu 22.04 system.
Creating a Java File
First, create a new file with a .java
extension, for example, HelloWorld.java
. Open a text editor and add the following code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Compiling the Java Code
To compile the Java code, open a terminal and navigate to the directory where you saved the HelloWorld.java
file. Then, run the following command:
javac HelloWorld.java
This will compile the Java code and generate a HelloWorld.class
file, which contains the compiled bytecode.
Running the Java Program
To run the compiled Java program, use the following command:
java HelloWorld
This will execute the main()
method in the HelloWorld
class and output the message "Hello, World!" to the console.
Understanding the Compilation and Execution Process
The process of compiling and running Java code can be visualized using the following mermaid diagram:
graph TD
A[Java Source Code] --> B[Java Compiler]
B --> C[Java Bytecode]
C --> D[Java Virtual Machine]
D --> E[Executed Program]
The Java compiler (javac
) takes the Java source code and generates Java bytecode, which can then be executed by the Java Virtual Machine (java
).
By understanding this process, you can effectively compile and run Java programs on your Ubuntu 22.04 system.