A Java package creates a namespace and an access boundary. Its declaration, directory layout, imports, qualified names, and module or build configuration must agree.
In larger Java applications, packages become architecture boundaries. Keep controller, service, model, repository, and utility classes in clear packages so imports explain the project structure instead of becoming random file locations.
Keep package declarations, source directories, imports, qualified names, and access modifiers aligned so namespace boundaries are visible in code and builds.
The package statement must be the first non-comment line in a Java file. The folder path should match the package name.
// File: com/tutorialslogic/app/Main.java
package com.tutorialslogic.app;
public class Main {
public static void main(String[] args) {
System.out.println("Package demo");
}
}
Use import to refer to classes from other packages by simple name. java.lang is imported automatically.
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class ImportDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Java");
System.out.println(LocalDate.now());
}
}
When using packages from the command line, compile from the source root and run using the fully qualified class name.
javac -d out src/com/tutorialslogic/app/Main.java
java -cp out com.tutorialslogic.app.Main
The package statement must be the first non-comment statement in a Java file. Imports let you use classes from other packages without writing the full name every time.
Packages group related Java classes under a namespace. They prevent name conflicts, make large projects easier to browse, and show which part of the application a class belongs to. A class named UserService inside com.shop.users communicates much more than a loose UserService file in a flat folder.
Imports do not copy code into the file. They simply let the compiler resolve a class name without writing the full package every time. Built-in packages such as java.util and java.time are used constantly, while custom packages are created to match modules such as controllers, services, models, and repositories.
package com.school.reports;
import java.time.LocalDate;
public class AttendanceReport {
public String heading() {
return "Attendance report for " + LocalDate.now();
}
}
The source path normally mirrors the package name, such as com/example/app.
Named packages import and organize code reliably; default-package classes are awkward to reuse.
It shortens a type name in source code. It does not load or copy the class.
Practice, interview questions, and compiler links for Core Java.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.