Java — Organizing code across files
A Java package gives related classes a namespace. Import the packaged helper in Main and compile both source files so the entry point can call the helper’s static method.
A simple example
Import a type from a package
- Start with 1, 2, 3
- Do this Import List and read its size
- Result 3
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
System.out.println(List.of(1, 2, 3).size());
}
}
3
Share a function between source files
The package statement gives BoxMath its fully qualified name. Its public static method can be called without creating an object. Compile both sources before launching Main.
A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.
Run the example
Java 17 or later. Run these commands from the directory containing the example.
javac -d . boxes/BoxMath.java Main.java
java Main
package boxes;
public class BoxMath {
public static int remaining(int capacity, int used) {
return capacity - used;
}
}
import boxes.BoxMath;
class Main {
public static void main(String[] args) {
System.out.println(BoxMath.remaining(8, 3));
}
}
5
Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.
Try it yourself
Change the used count from 3 to 8 in the caller.
Check your answer
Running the same command prints 0. No change to the helper is needed.