Import statements let you use code from other places easily. They save time and keep your code clean.
Import statement usage in Java
import packageName.ClassName; // or to import all classes in a package import packageName.*;
The import statement must be placed at the top of your Java file, before any class definitions.
Using * imports all classes in a package but does not import sub-packages.
import java.util.Scanner;import java.util.*;import static java.lang.Math.PI;
This program uses the Scanner class to read user input. The import statement lets us use Scanner without writing java.util.Scanner every time.
import java.util.Scanner; public class ImportExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!"); scanner.close(); } }
Import statements do not import code automatically; they just let you use names without full paths.
If you forget to import a class, Java will show an error saying it cannot find the symbol.
You can also use fully qualified names without import, but it makes code longer and harder to read.
Import statements help you use classes from other packages easily.
Place import statements at the top of your Java file.
You can import single classes or all classes from a package using *.
