Explain the importance of import keyword in java?

Java 8Object Oriented ProgrammingProgramming

In Java classes and interfaces related to each other are grouped under a package. 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 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 class path 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.

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 the Java.Util Package.

Example

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);
   }
}

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
raja
Published on 05-Jul-2019 11:37:01
Advertisements