0
0
Javaprogramming~15 mins

Import statement usage in Java

Choose your learning style8 modes available
menu_bookIntroduction

Import statements let you use code from other places easily. They save time and keep your code clean.

When you want to use a class from another package without writing its full name every time.
When you want to organize your code by using libraries or built-in Java classes.
When you want to avoid repeating long package names in your code.
When you want to use multiple classes from the same package.
When you want to make your code easier to read and maintain.
regular_expressionSyntax
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.

emoji_objectsExamples
line_end_arrow_notchThis imports only the Scanner class from the java.util package.
Java
import java.util.Scanner;
line_end_arrow_notchThis imports all classes from the java.util package, like Scanner, ArrayList, etc.
Java
import java.util.*;
line_end_arrow_notchThis imports the static constant PI from the Math class, so you can use PI directly.
Java
import static java.lang.Math.PI;
code_blocksSample Program

This program uses the Scanner class to read user input. The import statement lets us use Scanner without writing java.util.Scanner every time.

Java
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();
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Import statements do not import code automatically; they just let you use names without full paths.

line_end_arrow_notch

If you forget to import a class, Java will show an error saying it cannot find the symbol.

line_end_arrow_notch

You can also use fully qualified names without import, but it makes code longer and harder to read.

list_alt_checkSummary

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 *.