Skip to content
C

import

import is used to bring in a class or an entire package from elsewhere, so it can be used in your current file without typing its full package path every single time.


1. What is import?

import is used to bring in a class or an entire package from elsewhere, so it can be used in your current file without typing its full package path every single time.

2. Why is it used?

Without import, you'd have to write out a class's complete path (like java.util.Scanner) every time you use it. import lets you simply write Scanner after importing it once at the top of the file.

3. Real-Life Example

Think of saving a frequently called contact under a short name in your phone, instead of typing their full phone number every single time you want to call them. import gives you this same kind of shortcut for using classes.

4. Syntax

java
import packageName.ClassName; import packageName.*; // imports all classes in that package

5. Example Program

java
import java.util.Scanner; public class ImportDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Scanner class imported and ready to use."); } }

Output:

Scanner class imported and ready to use.

6. Key Points to Remember

  • Classes inside java.lang (like String and System) are automatically available, without needing an explicit import.
  • Using packageName.* imports all classes in that package, but not classes in its sub-packages.
  • Import statements must appear after the package statement (if present) and before the class definition.