Why do we use import statement in Java? Where it should be included in the class?


The import statement can be used to import an entire package or sometimes import certain classes and interfaces inside the package. The import statement is written before the class definition and after the package statement(if there is any). Also, the import statement is optional.

A program that demonstrates this in Java is given as follows:

Example

 Live Demo

import java.util.LinkedList;

public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Apple");
      l.add("Mango");
      l.add("Cherry");
      l.add("Orange");
      l.add("Pear");
      System.out.println("The LinkedList is: " + l);
   }
}

Output

The LinkedList is: [Apple, Mango, Cherry, Orange, Pear]

Now let us understand the above program.

The LinkedList class is available in the java.util package. The import statement is used to import it. Then LinkedList l is created. LinkedList.add() is used to add a elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows:

LinkedList<String> l = new LinkedList<String>();
l.add("Apple");
l.add("Mango");
l.add("Cherry");
l.add("Orange");
l.add("Pear");
System.out.println("The LinkedList is: " + l);

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements