# What are the best practices to keep in mind while using packages in Java?

Java 8Object Oriented ProgrammingProgramming

You can create the .class files of all the Java classes and interfaces related to each other in one folder automatically by declaring them under same package. A package is nothing but a directory storing classes and interfaces of a particular concept.

## Creating a package

You can create a package and add required classes/interfaces in it just by declaring the package on the top of the Class/Interface files using the keyword package as −

Package package_name;

## Example

Following Java program, demonstrates the declaration of a package in Java.

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

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.

## Naming conventions and best practices for packages

While choosing a package name you need to keep the following points in mind.

• The name of the package should be in small letters.
• It is suggested to start the name of the package with the top level domain level followed by sub domains, ex: com.example.tutorialspoint.

## Points to remember

In addition to the above conventions you need to keeps the following points in mind while creating packages −

• Group the classes (of same functionality/concept) that are likely to undergo similar changes, together.
• Create sub packages according to the functionality as −
com.tutorialspoint.tutorix.classes
• Group the classes that are commonly reused together. Try to keep the packages simple and compact.
Published on 02-Aug-2019 11:36:06