Compiling Your Java Program
After creating your Java file, the next step is to compile it. Compilation is the process of converting human-readable Java code into bytecode that the Java Virtual Machine (JVM) can execute.
The Java Compilation Process
When you compile a Java program:
- The Java compiler (
javac
) reads your .java
file
- It checks for syntax errors
- If no errors are found, it generates a
.class
file containing bytecode
Compiling Your HelloWorld Program
Now, let's compile the Java file you created:
-
Navigate to the source directory:
cd ~/project/java-hello-world/src
-
Run the Java compiler with your file:
javac com/example/hello/HelloWorld.java
If there are no errors in your code, the command will complete without any output. This means the compilation was successful.
- Verify that a
.class
file was created:ls -l com/example/hello/
You should see output similar to:
total 8
-rw-r--r-- 1 labex labex 416 ... HelloWorld.class
-rw-r--r-- 1 labex labex 135 ... HelloWorld.java
The HelloWorld.class
file is the compiled bytecode that can be executed by the JVM.
Handling Compilation Errors
If you made a mistake in your code, the compiler would display error messages. For example, if you forgot to include a semicolon at the end of a statement, you would see an error similar to:
com/example/hello/HelloWorld.java:5: error: ';' expected
System.out.println("Hello, World!")
^
1 error
If you encounter any errors, go back to your Java file, fix the issues, and try compiling again.