Creating a Simple Java Application
Let us begin by creating a simple Java application that we will package into a JAR file. This will help us demonstrate and later fix the 'no main manifest attribute' error.
Create the Java Class
First, create a directory for our Java source files and navigate to it:
cd ~/project/src/com/example
Now, open the editor and create a new file named HelloWorld.java
in this directory:
- Click on the "Explorer" icon in the left sidebar of the WebIDE
- Navigate to
/home/labex/project/src/com/example
- Right-click and select "New File"
- Name the file
HelloWorld.java
Add the following code to the HelloWorld.java
file:
package com.example;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
This is a basic Java program with a main
method that will print "Hello, World!" to the console when executed.
Compile the Java Class
Now, let us compile our Java class. Return to the terminal and navigate to the project root directory:
cd ~/project
Compile the Java file using the javac
command:
javac -d . src/com/example/HelloWorld.java
This command compiles the Java source file and places the compiled class file in the appropriate directory structure based on the package name.
You should now have a compiled class file at ~/project/com/example/HelloWorld.class
. You can verify this with:
ls -l com/example/
The output should show the HelloWorld.class
file:
total 4
-rw-r--r-- 1 labex labex 426 [date] HelloWorld.class
Create a Basic JAR File Without a Manifest
Now, let us create a JAR file without specifying a main class in the manifest. This will allow us to reproduce the 'no main manifest attribute' error:
jar cf HelloWorld.jar com/
This command creates a JAR file named HelloWorld.jar
that includes the compiled class file.
Try to Run the JAR File
Now that we have created our JAR file, let us try to run it:
java -jar HelloWorld.jar
You will see the error message:
no main manifest attribute, in HelloWorld.jar
This is the error we are learning to fix. The JVM cannot find the main class to execute because we did not specify it in the JAR's manifest.