How to import classes from within another directory/package in Java?

Java 8Object Oriented ProgrammingProgramming

In Java classes and interfaces related to each other are grouped under a package. The package is nothing but a directory storing classes and interfaces of a particular concept. For example, all the classes and interfaces related to input and output operations are stored in the java.io package.

There are two types of packages namely user-defined packages and built-in packages (pre-defined)

The import keyword

Whenever you need to use the classes from a particular package −

  • First of all, you need to set a classpath for the JAR file holding the required package.

  • Import the required class from the package using the import keyword. While importing you need to specify the absolute name (including the packages and sub-packages) of the required class.

Example

In the following example we are trying to read a string value representing the name of the user from key-board (System.in). For this, we are using the scanner class of Java. Util Package.

 Live Demo

public class ReadingdData {
   public static void main(String args[]) {
      System.out.println("Enter your name: ");
      Scanner sc = new Scanner(System.in);
      String name = sc.next();
      System.out.println("Hello "+name);
   }
}

Output

Compile-time error

Since we are using a class named Scanner in our program and haven’t imported it in our program. On executing, this program generates the following compile-time error −

ReadingdData.java:6: error: cannot find symbol
      Scanner sc = new Scanner(System.in);
      ^
   symbol: class Scanner
   location: class ReadingdData
ReadingdData.java:6: error: cannot find symbol
      Scanner sc = new Scanner(System.in);
      ^
   symbol: class Scanner
location: class ReadingdData
2 errors

To resolve this error, add the import statement importing the scanner class on the top of the program as −

Example

 Live Demo

import java.util.Scanner;
public class ReadingdData {
   public static void main(String args[]) {
      System.out.println("Enter your name: ");
      Scanner sc = new Scanner(System.in);
      String name = sc.next();
      System.out.println("Hello "+name);
   }
}

Output

Enter your name:
krishna
Hello krishna
raja
Published on 06-Sep-2019 16:07:48
Advertisements