In this blog post, we’ll explore how to compile and run Java code with packages, demonstrate the use of the classpath option for alternate directories, and delve into creating and executing Java Archive (JAR) files.
Organizing Code with Packages
Packages are Java’s way of structuring the codebase. They allow developers to group related classes and interfaces together. Let’s start by creating two simple classes, Person
and Student
, each in its own file within a package named com.example
.
Person.java:
package com.example;
public class Person {
public void greet() {
System.out.println("Hello, I am a person!");
}
}
Student.java:
package com.example;
import com.example.Person; // Importing the Person class
public class Student {
public static void main(String[] args) {
Person person = new Person();
person.greet();
System.out.println("I am a student!");
}
}
Compiling Java Code
To compile the code, open your terminal or command prompt, navigate to the directory containing the source files, and use the javac
command.
javac com/example/Person.java com/example/Student.java
This command compiles both Person.java
and Student.java
. Ensure that the directory structure matches the package structure.
Running Java Code
After successful compilation, run the Student
class using the java
command.
java com.example.Student
The output should be:
Hello, I am a person!
I am a student!
Using an Alternate Directory with Classpath
Sometimes, you may want to compile and run your code from a different directory. The classpath option (-cp
or -classpath
) allows you to specify the location of compiled classes.
# Compile in the current directory but output class files to the 'bin' directory
javac -d bin com/example/Person.java com/example/Student.java
# Run the Student class with the classpath pointing to the 'bin' directory
java -cp bin com.example.Student
Creating and Running JAR Files
JAR files package Java classes and resources into a single file for distribution. To create a JAR file, use the jar
command.
cvf
in jar
Command:
c
Option: This option stands for “create.” It is used to create a new JAR file.v
Option: This option stands for “verbose.” It prints detailed information about the JAR creation process.f
Option: This option specifies the JAR file’s name. It must be followed by the filename of the JAR.
# Create a JAR file named 'myapp.jar' containing classes from the 'bin' directory
jar cvf myapp.jar -C bin .
# Run the JAR file
java -cp myapp.jar com.example.Student
cvf
: Specifies that we want to create a new JAR file (c
), display detailed information (v
), and specify the filename of the JAR (f
).myapp.jar
: The name of the JAR file that will be created.-C bin .
: This is crucial. It tells thejar
command to change to thebin
directory (-C bin
) before processing the files. The dot (.
) at the end includes all files from the specified directory.