Difference between import and package in Java?

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.

Creating a package

You can group required classes and interfaces under one package just by declaring the package at the top of the Class/Interface (file) using the keyword package as −

package com.tutorialspoint.mypackage;
public class Sample{
   public void demo(){
      System.out.println("This is a method of the sample class");
   public static void main(String args[]){
      System.out.println("Hello how are you......");

Compiling a program with a package

Unlike other programs to compile a program with a package, you need to use the –d option of the javac command specifying the destination path where you need to create the package.

javac –d . Sample.java

If you haven’t mentioned the destination path the package will be created in the current directory.

Executing the .class file created with in a package

To execute the byte code within a file you need to specify the absolute class name (name along with the package) as −

java com.tutorialspoint.mypackage.Sample
Hello how are you......

Accessing the contents of a package

To access the classes/interfaces that are grouped under a package, you need to add the location of the package in the classpath variable (or make sure the package is in the current directory) and import the class/interface of it using the import keyword.

import com.tutorialspoint.mypackage.Sample;
public class Test{
   public static void main(String args[]){
      Sample obj = new Sample();


This is a method of the sample class

Difference between import and package

As discussed above the package keyword is used to group certain classes and interface under one package and, the import keyword is used include/use the classes and interface from a package in the current program.

Updated on: 02-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started