Working with Packages and Imports
1. Creating Packages
| Element | Rule |
|---|---|
| Declaration | package com.example.app; first non-comment line |
| Directory | Must match: com/example/app/ |
| One per file | Each .java in exactly one package |
2. Understanding Package Naming Conventions
| Convention | Detail |
|---|---|
| All lowercase | com.example.app |
| Reverse domain | com.company.product |
| Avoid | Hyphens, digits at start, Java keywords |
3. Importing Classes
| Form | Example |
|---|---|
| Single | import java.util.List; |
| Wildcard | import java.util.*; |
| Static | import static java.lang.Math.PI; |
| Auto-imported | java.lang.* + same package |
4. Using Wildcard Imports (import java.util.*)
| Aspect | Detail |
|---|---|
| Scope | Top-level types in package only — NOT subpackages |
| No runtime cost | Resolved at compile time |
| Risk | Name conflicts if multiple wildcards |
5. Importing Static Members (import static)
Example: Static import
import static java.lang.Math.*;
import static org.junit.jupiter.api.Assertions.*;
double r = sqrt(pow(x, 2) + pow(y, 2));
assertEquals(expected, actual);
| Use | Caution |
|---|---|
| Math, asserts, factories | Improves readability |
| Avoid overuse | Hides origin of names |
6. Understanding Default Package
| Aspect | Detail |
|---|---|
No package declaration | Class is in default (unnamed) package |
| Limitations | Cannot be imported by other packages |
| Recommendation | Avoid for production code |
7. Resolving Package Conflicts
Example: Conflict resolution
import java.util.Date;
// java.sql.Date used via fully qualified name
java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
| Strategy | Detail |
|---|---|
| Single import wins | Specific import overrides wildcard |
| Fully qualified | Use full path for second name |
| Type alias | Not supported in Java |
8. Organizing Code with Packages
| Pattern | Layout |
|---|---|
| By layer | controller/, service/, repository/ |
| By feature | order/, payment/, user/ |
| DDD | domain/, application/, infrastructure/ |
9. Understanding CLASSPATH
| Form | Use |
|---|---|
| Env variable | CLASSPATH (avoid) |
| CLI flag | java -cp lib/*:. or -classpath |
| Modules JAVA 9+ | --module-path |
10. Compiling Packages
Example: javac with packages
javac -d out src/com/example/app/Main.java
java -cp out com.example.app.Main
| Flag | Use |
|---|---|
-d dir | Output directory |
-sourcepath src | Source roots |
--release N | Target Java version |