Java Packages & Import
In this page:
Standard Class Imports
A standard class import (import java.util.ArrayList;) makes one specific class available by its short name in the current file, without needing to write its fully qualified path every time it's used.
Example: Standard Class Imports
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(); // short name, no full path needed
list.add("a");
System.out.println(list);
}
}
Login to try C/C++/Java/PHP code in the editor
Wildcard Package Imports
A wildcard import (import java.util.*;) brings in every public class from a package at once, which is convenient but can obscure exactly which classes a file actually depends on.
Example: Wildcard Package Imports
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>(); // brings in every public class from java.util
list.add("a");
System.out.println(list);
}
}
Login to try C/C++/Java/PHP code in the editor
Static Imports
A static import (import static java.lang.Math.PI;) lets you reference a class's static member directly by name (PI) instead of qualifying it every time (Math.PI), which is handy for frequently used constants or methods.
Example: Static Imports
import static java.lang.Math.PI;
public class Main {
public static void main(String[] args) {
System.out.println(PI); // no Math. prefix needed
}
}
Login to try C/C++/Java/PHP code in the editor
Using Fully Qualified Names
You can always skip importing entirely and reference a class by its fully qualified name (java.util.List<String>), which is occasionally necessary to disambiguate two classes with the same simple name from different packages.
Example: Using Fully Qualified Names
public class Main {
public static void main(String[] args) {
java.util.List<String> list = new java.util.ArrayList<>(); // no import at all
list.add("a");
System.out.println(list);
}
}
Login to try C/C++/Java/PHP code in the editor
Implicitly Imported Packages
Classes in java.lang (like String, Object, and System) are available in every Java file automatically without any import statement, since that package is implicitly imported everywhere.
Example: Implicitly Imported Packages
public class Main {
public static void main(String[] args) {
String s = "Hello"; // java.lang.String, no import needed
System.out.println(s);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: