Packages & Imports in Java
Organise code into packages, use import statements, understand wildcard imports, and manage dependencies with Maven and Gradle.
What is a Package?
1. What is a Package?
A package is a namespace that groups related classes and interfaces together. It maps directly to a folder on disk. The `package` statement must be the first line in a Java source file.
2. Default Package
If no `package` statement is declared, the class belongs to the unnamed default package. Avoid this in real projects — it prevents other packages from importing the class.
Import Statements
1. Single Class Import
Use `import fully.qualified.ClassName` to bring a specific class into scope. This is the preferred style.
2. Wildcard Import
`import java.util.*` imports all public classes in the `java.util` package. It does NOT import sub-packages.
3. Static Import
`import static` lets you use static members (methods, constants) without qualifying them with the class name.
4. Fully Qualified Name (No Import)
You can always use the full class path inline without an import — useful when two packages have classes with the same name.
java.lang — Auto-imported Package
1. Always Available Classes
`java.lang` is the only package automatically imported in every Java file. It contains core classes like `String`, `Math`, `System`, `Integer`, `Object`, `Thread`, and more.