Java package

In a school, there will be many students. We will group those students by their Class. Few students will be in Class-5, few in Class-6, and so on. The same concept is with packages. Java package is a group of sub-packages, classes and interfaces. The entities which belong together, we will keep it in the same package.

Types of package

There are 2 types of packages

1 ) Built-In or Predefined java packages – The packages which are already available in the existing java libraries are known as Built-In packages. Java is a huge API that consists of already defined java classes and packages. This class and packages help us to achieve some default functionalities. Some examples of predefined java packages are:

  • java.io: Provides for system input and output through data streams, serialization and the file system.
  • java.lang: Provides classes that are fundamental to the design of the Java programming language.
  • java.math: Provides classes for performing arbitrary-precision integer arithmetic (BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal).
Predefined package

We can get all the predefined packages of Java 7 on oracle docs please refer to this link: https://docs.oracle.com/javase/7/docs/api/

2 ) User-defined packages – The packages defined by a user or a programmer are known as User-defined packages. As a programmer, if you want to define a class then you can create a package and write your class inside that package. Ex. We can write all the business-related classes under a service package. We can write all the database-related classes under the Dao package etc.

Create java package

We can create a java package using a package keyword. package statement should be the first statement of a java class. If you are not explicitly defining any package then that class comes under the default package.

Compile and Run a java package

If you create a java package and a class inside some java editor like Eclipse or Intellij then as a developer we don’t have to think about how to compile and run that program. We just have to click a button and the editor will compile and run the program.

But say we have written a java package program in a text editor like notepad then we have to make use of the below commands.

Compile a class

javac -d directoryName javaFileName

-d Specify where to place generated class files

Run a class

java packageName.className

Run this command from the root directory
package com.getinputs;

public class PackageDemoTextEditor {

  public static void main(String[] args) {

    System.out.println("Hello this package is created in Notepad text editor");
  }
}
D:\Programs>dir

Directory of D:\Programs                                                                                                                                                                                                                                                                                                                                                                                                             05-01-2022  12:06    <DIR>          .                                                                                                                                                                              05-01-2022  12:06    <DIR>          ..                                                                                                                                                                             05-01-2022  11:00               200 PackageDemoTextEditor.java                                                                                                                                                                    1 File(s)            200 bytes                                                                                                                                                                                     2 Dir(s)  189,611,556,864 bytes free

D:\Programs>javac -d . PackageDemoTextEditor.java

D:\Programs>dir

Directory of D:\Programs                                                                                                                                                                                                                                                                                                                                                                                                             05-01-2022  12:09    <DIR>          .                                                                                                                                                                              05-01-2022  12:09    <DIR>          ..                                                                                                                                                                             05-01-2022  12:09    <DIR>          com                                                                                                                                                                            05-01-2022  11:00               200 PackageDemoTextEditor.java                                                                                                                                                                    1 File(s)            200 bytes                                                                                                                                                                                     3 Dir(s)  189,611,556,864 bytes free 

D:\Programs>cd com\getinputs

D:\Programs\com\getinputs>dir

 Directory of D:\Programs\com\getinputs                                                                                                                                                                                                                                                                                                                                                                                               05-01-2022  12:09    <DIR>          .                                                                                                                                                                              05-01-2022  12:09    <DIR>          ..                                                                                                                                                                             05-01-2022  12:09               502 PackageDemoTextEditor.class                                                                                                                                                                   1 File(s)            502 bytes                                                                                                                                                                                     2 Dir(s)  189,611,556,864 bytes free 

D:\Programs\com\getinputs>cd ../../ 

D:\Programs>java com.getinputs.PackageDemoTextEditor
Hello this package is created in Notepad text editor

Subpackages in java

A package inside another package is known as a subpackage in java. If we have to split a parent package further then we can make use of the subpackage. Some examples of predefined java sub-packages are:

  • java.lang.reflect: Provides classes and interfaces for obtaining reflective information about classes and objects.
  • java.nio.file: Defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems.
  • java.util.concurrent: Utility classes commonly useful in concurrent programming.

We can get all the predefined sub-packages of Java 7 on oracle docs please refer to this link: https://docs.oracle.com/javase/7/docs/api/

Import java package

We can import a package in java using an import keyword. Once we import a package we can access the classes and interfaces of that imported package in the current package.

If Class-A has to use some methods of Class-B and both the classes are in the same package then we don’t have to specify import statement in Class-A because Class-B members get imported to Class-A by default.

We can import a package in 3 ways

1 ) import package-name.* – All the classes and subclasses of the imported package will be accessible. Sub packages will not be imported.

package com.suraj;

public class Operations {

  public void add(int a, int b) {
    System.out.println("Addition of 2 numbers is : " + (a + b));
  }

  public void multiply(int a, int b) {
    System.out.println("Multiplication of 2 numbers is : " + (a * b));
  }
}
package com.suraj.utils;

public class Addition {

  public void add(int a, int b) {
    System.out.println("Addition of 2 numbers is : " + (a + b));
  }
}
package com.getinputs;

import com.suraj.*;

public class PackageDemo {

  public static void main(String[] args) {

    Operations operations = new Operations();

    operations.add(5, 10);
    operations.multiply(5, 10);

    Addition addition = new Addition();
  }
}

Output : Exception in thread "main" java.lang.Error: Unresolved compilation problems: Addition cannot be resolved to a type

Note* utils is a subpackage of com.suraj . We have imported com.suraj.* still the subpackage is not imported and a compile-time exception is thrown. Hence we have to import a subpackage as well.

package com.getinputs;

import com.suraj.*;
import com.suraj.utils.Addition;

public class PackageDemo {

  public static void main(String[] args) {

    Operations operations = new Operations();

    operations.add(5, 10);
    operations.multiply(5, 10);

    Addition addition = new Addition();
    addition.add(20, 30);
  }
}

Output : Addition of 2 numbers is : 15
         Multiplication of 2 numbers is : 50
         Addition of 2 numbers is : 50

2 ) import package-name.class-name – We will be able to access only the specific class of the imported package. We will not be able to access any other class of that package.

import com.suraj.Operations;

public class PackageDemo {

  public static void main(String[] args) {

    Operations operations = new Operations();

    operations.add(5, 10);
    operations.multiply(5, 10);
  }
}

Output : Addition of 2 numbers is : 15
         Multiplication of 2 numbers is : 50

Note* We will not be able to import any other class from com.suraj package.

3 ) Fully qualified name – We can directly access the specific class. We don’t have to use the import keyword. We just have to use the Fully Qualified name of a class when making use of it.

package com.getinputs;

public class PackageDemo {

  public static void main(String[] args) {

    com.suraj.Operations operations = new com.suraj.Operations();

    operations.add(5, 10);
    operations.multiply(5, 10);
  }
}

Output: Addition of 2 numbers is: 15
        Multiplication of 2 numbers is: 50

Advantages of package

1 ) Easy Maintenance: As we keep the classes or interfaces of similar functionality in a similar package so it will be easier to maintain.

2 ) Controlled Access: The package provides access protection to default and protected members.

Default member is accessible by classes in the same package.

package com.getinputs;

public class Operations {

  void add(int a, int b) {
    System.out.println("Addition of 2 numbers is : " + (a + b));
  }

  void multiply(int a, int b) {
    System.out.println("Multiplication of 2 numbers is : " + (a * b));
  }
}
package com.getinputs;

public class PackageDemo {

  public static void main(String[] args) {

    Operations operations = new Operations();

    operations.add(5, 10);
    operations.multiply(5, 10);
  }
}

Output: Addition of 2 numbers is: 15
        Multiplication of 2 numbers is: 50

A protected member is accessible by classes in the same package and its subclasses.

package com.getinputs;

public class Operations {

  protected void add(int a, int b) {
    System.out.println("Addition of 2 numbers is : " + (a + b));
  }

  protected void multiply(int a, int b) {
    System.out.println("Multiplication of 2 numbers is : " + (a * b));
  }
}
package com.getinputs;

public class PackageDemo {

  public static void main(String[] args) {

    Operations operations = new Operations();

    operations.add(5, 10);
    operations.multiply(5, 10);
  }
}

Output: Addition of 2 numbers is: 15
        Multiplication of 2 numbers is: 50

3 ) Naming conflicts: If we want to provide the same name to 2 different classes then we can keep them in separate packages. Ex. Date class is defined in java.util and java.sql package.

Static import in java

We can access all the static members of a class using a static import. We don’t have to use a class name or an object reference to call a static member. Static members can be accessed directly.

Ex. In the Predefined Math class of java, we are having many static methods and we can use those static methods directly by doing a static import.

  • static double max(double a, double b) : Returns the greater of two double values.
  • static int max(int a, int b) : Returns the greater of two int values.
package com.suraj;

public class Operations {

  public static void add(int a, int b) {
    System.out.println("Addition of 2 numbers is : " + (a + b));
  }

  public static void multiply(int a, int b) {
    System.out.println("Multiplication of 2 numbers is : " + (a * b));
  }
}
package com.getinputs;

import static com.suraj.Operations.*;

public class PackageDemo {

  public static void main(String[] args) {

    add(5, 10);

    multiply(5, 10);
  }
}

Output: Addition of 2 numbers is: 15
        Multiplication of 2 numbers is: 50

In this article, we have covered java package, subpackage, types of package, creating and importing a package along with its advantages. I hope you found this article interesting and valuable. Please share this article with your friends and help me grow. If you are having any concerns or questions about this article please comment below. If you want to get in touch with me please visit the Contact Me page and send me an email.