
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Import Classes from Another Directory Package in Java
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.
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
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