Working with Packages and Imports

1. Creating Packages

ElementRule
Declarationpackage com.example.app; first non-comment line
DirectoryMust match: com/example/app/
One per fileEach .java in exactly one package

2. Understanding Package Naming Conventions

ConventionDetail
All lowercasecom.example.app
Reverse domaincom.company.product
AvoidHyphens, digits at start, Java keywords

3. Importing Classes

FormExample
Singleimport java.util.List;
Wildcardimport java.util.*;
Staticimport static java.lang.Math.PI;
Auto-importedjava.lang.* + same package

4. Using Wildcard Imports (import java.util.*)

AspectDetail
ScopeTop-level types in package only — NOT subpackages
No runtime costResolved at compile time
RiskName 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);
UseCaution
Math, asserts, factoriesImproves readability
Avoid overuseHides origin of names

6. Understanding Default Package

AspectDetail
No package declarationClass is in default (unnamed) package
LimitationsCannot be imported by other packages
RecommendationAvoid 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());
StrategyDetail
Single import winsSpecific import overrides wildcard
Fully qualifiedUse full path for second name
Type aliasNot supported in Java

8. Organizing Code with Packages

PatternLayout
By layercontroller/, service/, repository/
By featureorder/, payment/, user/
DDDdomain/, application/, infrastructure/

9. Understanding CLASSPATH

FormUse
Env variableCLASSPATH (avoid)
CLI flagjava -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
FlagUse
-d dirOutput directory
-sourcepath srcSource roots
--release NTarget Java version