A package is a namespace for types. It lets two projects both have a Util without colliding, groups related API, and is the unit of package-private access.
com.example.util.Mental model: the full name of a type is package.Type. import only saves typing. It does not “load a library” the way a C include copies text. The compiler and class loader still need the class on the classpath (or module path).
package com.example.util;
public class Strings {
}
package is the first declaration in the file (comments and Javadoc may precede it).…/com/example/util/Strings.java.javac writes matching directories. Run with the class name com.example.util.Strings and the root of that tree on the classpath.javac -d out src/com/example/util/Strings.java java -cp out com.example.util.Strings
Default package: no package line. Fine for one-file homework. Types there cannot be imported from a named package. Do not ship a library in the default package.
import java.util.ArrayList; import java.util.List; import static java.lang.Math.PI; List<String> xs = new ArrayList<>(); double tau = 2 * PI;
| Form | Meaning |
|---|---|
import pkg.Type; | One type |
import pkg.*; | Types in that package only — not subpackages |
import static pkg.Type.NAME; | A static member as a simple name |
import static pkg.Type.*; | All static members — easy to overuse |
java.util.Date vs java.sql.Date).import java.util.*; does not import java.util.concurrent.ConcurrentHashMap.Every compilation unit implicitly imports java.lang.*. String, System, Math, Integer, Object, Exception do not need an import.
java.lang to use String” — false.java.util, java.io, java.time, …String in another package shadows the simple name — do not.public types are visible everywhere the classpath can see them.protected members: subclasses and the same package (see Modifiers).package com.example.api;
public class Service {
Helper h = new Helper(); // same package — OK
}
class Helper { } // package-private
Import is compile-time sugar. At runtime the JVM loads com.example.util.Strings by searching the classpath / module path.
ClassNotFoundException / NoClassDefFoundError: the class was expected and not found (or failed to initialize).javac or the IDE reports a mismatch.java Strings instead of java com.example.util.Strings.import pkg.* includes subpackages.of came from.java.lang. Never invent your own String.-d and run -cp without an IDE.module-info.java is a later, optional layer (see JVM and runtime).~ Good luck with your revision! ~