In Java, the import statement is used to access predefined classes, interfaces, and packages. It allows programmers to use built-in Java libraries or user-defined packages without writing full package paths every time.
The import statement comes after the package declaration (if any) and before the class definition. Java provides thousands of built-in classes inside packages like java.util, java.io, and java.lang.
// Importing a single class from java.util package
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
}
}
// Importing all classes from a package using wildcard
import java.util.*;
public class WildcardExample {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
}
}
The compiler uses the import statement to locate the required class definitions. Without importing, you would need to write the full package path like java.util.Scanner every time.
The code below uses the Random class but is missing an import. Click the correct import statement to fix the compiler error!
java.lang package is imported automaticallyArrayList with and without import