Java Packages

Java Packages

package is a bundle or group of classes, interfaces, sub packages combined in a one file. there are two types of packages in java 1) built-in 2) User-defined

In java programming are there are several built-in packages created by the official java developers. for example for taking a input from the user ,we use scanner class

import java.util.Scanner
  • import is a keyword to use packages in program
  • java is a main package ,or top level package
  • util is a sub-package
  • Scanner is a class inside the util package

Advantages of packages in java

  • Name Conflicts: if you have two classes with the same name, that would become a conflict to run the program, so you use name different packages for two same class names, there will be no issue
  • Code Maintenance: packages in java are useful when you have a large project,you cant maintain bulky code, so we can split the code into packages and use it in the program. when you need something like any class, you can quickly locate it and use it, which improves efficiency.
  • Reusability: once the package is created, you can use the same package to any number of programs, you don’t need to rewrite the whole program.
  • Java package provides access protection

Creating a simple package in java

packages can be created using package keyword in java.


package PackageName;


package basicpack;
public class basic{
public static void main(String args[]){
System.out.println("This is a Basic PAckage");

Save the above code in the file name as its class name,here in the example file name saved is

first after writing a package, you should compile and to test your package you can run it

To compile the program ,use the below command

javac -d directory

If your package is in the present working directory,then you can use . (dot)

javac -d .

to run the package use below command

java PackageName.ClassName

For better understanding check the screenshot provided below, for the package basicpack and the file name is

Java Packages Output

If use any custom IDE’s like eclipse, Atom, VScode, you have so many plugins to use package in java , I use VScode IDE ,so i use java saber plugin to configure java packages

Accessing packages

Packages can be accessed using the import keyword.

To import complete package you can follow below syntax.

Syntax to import complete package

import PackageName.*;

if the package name end with .* then, all classes and interfaces except sub packages are accessabel


basic.javapackage basicpack;
public class basic{
public static void main(String args[]){
System.out.println("This is a Basic PAckage");
import basicpack.*;
class B{
static void main(String args[]){
basic obj = new basic();
Last updated on by vishal devxo