Packages in Java with example programs - Scientech Easy

Packages in Java with example programs

In this tutorial, we will discuss packages in Java with example and programs. Do you know that one of the main advantages of the Java language is that it has defined a very clear and systematic packaging mechanism for categorizing and managing its large APIs. In Java, APIs consists of one or more packages where packages consist of many classes, classes contain several methods and fields. When you create any program in Java, you should create a  proper folder structure for better reusability, naming conflict, and maintenance but How? Let's see in detail.

Package in Java

A package is nothing but a physical folder structure that contains a group of related classes, interfaces, and sub packages according to their functionality such as graphics, audio, text, or project. It provides a convenient way to organize your work. 
A real-life example is when you download a movie, song or game, you make a different folder for each category like movie, song etc. In the same way, when you create any software in Java programming language, they contain hundreds or thousands of individual classes and interfaces that must be organized into a meaningful package name to make proper sense and reusing these packages in other programs could be easier. 

Advantages of using packages in Java

Maintenance: Java packages are used for proper maintenance. If any developer newly joined a company, he can easily reach to files needed.
Reusability: We can place the common code in a common folder so that everybody can check that folder and use it whenever needed.
Name conflict: Packages help to resolve the naming conflict between the two classes with the same name.
➲ It also helps in organizing the files within our project. 
➲ It provides access protection.

Types of Package in Java

There are two types of packages in Java.
1. User-defined package: The package which is defined by the user is called a User-defined package. It contains user-defined classes and interfaces.
Coding convention to declare the User-defined Package in real-time:
While developing your project, you must follow some convention regarding packages declaration. Let's take an example to understand the convention. See below image.
packages in java with example programs,java packages,how to create package in java,list of packages in java,types of packages in java,importing packages in java.
User-defined Package
1. Suppose you are working in IBM and domain name of IBM is You can declare the package by reversing the domain like this:
where com ➝ It is generally company specification name and the folder starts with com which is called root folder.
            ibm ➝ Company name where the product is developed. It is the subfolder.
2. hdfc ➝ Client name for which we are developing our product or working for the project.
3. loan ➝ Name of the project.
4. homeloan ➝ It is the name of the modules of the loan project. There are a number of modules in the loan project like a Home loan, Car loan, or Personal loan. Suppose you are working for Home loan module. This is a complete packages structure like professional which is adopted in the company.
Note: Keep in mind Root folder should be always the same for all the classes.
Other examples are:

2. Predefined package: Predefined packages are those which are developed by Sun Microsystem. These packages consist of a large number of predefined classes and interfaces that are part of Java APIs. APIs contain the following packages:
packages in java with example programs,how to create package in java,importing packages in java.
Types of Packages

Core packages:
1. Java.lang: The Java language package provides the classes and interfaces that form the core of the Java language and the JVM. For example, classes, object, String, Thread, predefined data types etc. It is imported automatically into the Java programs.
2. It provides a set of I/O streams which are used to read and write data to files.
3. Java util: It contains a collection of the utility classes and related interfaces which implement data structures like LinkedList, Dictionary, HashTable, stack, vector, Calender, data utility etc.
4. It contains networking classes and interfaces for networking operation.

Window Toolkit and Applet:
1. Java.awt: The Abstract window toolkit packages contain the GUI(Graphical User Interface) elements such as buttons, lists, menus and text areas.
2. Java.awt.image: It contains classes and interfaces for creating image and colors.
3. Java.applet: It is used for creating applets.

Remember notes: Java contains a group of packages which contains the group of classes and interfaces. These classes and interfaces contain groups of methods. For example, Java contains Java.lang package which contains classes like String, StringBuffer, StringBuilder etc. The String class contains number of methods like length(), toUpperCase() etc. 

Note: In Java 1.8 contains 14 Predefined packages which contain approx 150 sub-packages. These sub packages contain above 7000 classes which contain approx 7 lakh methods. The name of the 14th predefined package is Java.times package. Which is not in Java 1.7 version. Out of 14th predefined packages, The default package in Java is the Java.lang package. Default package means you import or not, it's automatically imported.
Let's see examples program to clear the concepts.
Example 1
Program source code 1:

    // Save as Step 1: Declare package name by reversing domain name, project name 'java' and module name is core java. package; Step 2:Declare class name. class Example{ public static void main(String[] args){ System.out.println(" My first basic example"); } }
How to compile java package?
If you are not using any IDE, you follow the syntax given below:
 To Compile the application:  javac -d directory javafilename.
Here, javac means java compiler. 
-d means directory. It creates the folder structure.
.(dot) means the current directory. It places the folder structure in the current working directory.
For example:
          javac where is the file name.
So in this way, you must compile application if the application contains a package statement.
After the compilation, you can see the folder structure in your system like this:
  |---> scientecheasy
      |------> java
         |------> corejava
             |------> Example.class

How to run Java package program?
We have to use the fully qualified name to execute the code. The fully qualified name means class name with complete package structure.
To Run:   java

    Output: My first basic example.

Importing packages in Java

How to access package from outside the package?

There are three approaches to access package from outside the other package.
1. import package.*;
2. import package.classname;
3. Using fully qualified name.

1. Using package.*
The import is a keyword which is used to make the classes and interfaces of other packages accessible to the current package.
If we use package.*, all the classes and interfaces of this package can be accessed from outside the packages.
Let's see a simple example:
Program source code 2: Follow all the above steps of program source code 1.
    // Save by package com.scientecheasy.calculate; // Declare public with class name otherwise it cannot be accessible due to default which is accessible within the same package. public class Sum{ // Declare instance variable. int a=20; int b=30; // Decalare method public void cal(){ int sm=a+b; System.out.println("Sum: " +sm); }
    // Save package com.maths.calculator; // Now import package. import com.scientecheasy.calculate.*; class SumTest{ public static void main(String[] args) { // Create object of class and call the method using reference variable s. Sum s=new Sum();; } }
    Output: 50
2. Using packagename.classname
If we import package.classname, we can only access declared class of this package.
Example: Suppose scientecheasy have information about the Dhanbad city and TCS need this information.
Program source code 3:  Here, We are declaring two modules Dhanbad and Tcs. TCS is using Dhanbad class but Both have the different package. So whenever we are using other package class, you must import the package first of all.

    // Declare the complete package statement. package com.scientecheasy.state.cityinfo; public class Dhanbad{ public void stateInfo(){ System.out.println("Dhanbad is the first major city of Jharkhand"); } public void cityInfo(){ System.out.println("Dhanbad city is called coal capital city of India."); } }
    // Declare the complete package statement for TCS. package com.tcs.state.requiredinfo; // Import the package with classname. import com.scientecheasy.state.cityinfo.dhanbad; class Tcs{ public static void main(String[] args){ Dhanbad d=new Dhanbad(); d.stateinfo(); d.cityinfo(); } }
    Output: Dhanbad is the first major city of Jharkhand. Dhanbad city is called coal capital city of India.
3. Using the fully qualified name
If you use the fully qualified name, there is no need of using import statement but in this case, only declared class of this package can be accessible. It is generally used when two packages have the same class name. 
Let's take scenario. See the below image.
In the com package, there are two sub-packages scien and tech. In scien, two class file A.javaand In tech, three class files,, and Now see the above requirement. 
Program source code 4:
    package com.scien; import; class B { // 1 void m3() { // 2 System.out.println("Hello Java"); } public static void main(String[] args){ A a=new A(); // 3 a.m1(); // 4 A a1=new A(); // 5 a1.m2; // 6 B b=new B(); b.m3(); } }
Will above code compile?
No: because line 3 does say anything about class A form which package (scien or tech) it is referring.
No: because line 5 also not saying anything about class A from which package(scien or tech) it is referring.
No: because line 4 and 6 will get confused to call the method of which package's class. Here, the compiler will be also confused.
In this case, import is not working. So you remove the import statement and use the fully qualified name.
    package com.scien; class B { // 1 void m3() { // 2 System.out.println("Hello Java"); } public static void main(String[] args){ A a=new A(); // 3 keep as it is because it is from same package "scien". a.m1(); // 4 a1=new; // 5 It will direct go to tech package and call the method m2. a1.m2; // 6 B b=new B(); b.m3(); } }
    Output: Hi Hello Hello Java
Suppose you are not using public with m2() method then it will give error " The method m2() from the type A is not visible" because it is a default and default access modifier cannot be accessed from outside the package. 
Points to remember:
1. While importing another package, package declaration must be the first statement and followed by package import.
2. A class can have only one package statement but it can be more than one import package statements. 
3. import can be written multiple times after the package statement and before the class statement.
4. You must declare the package with root folder name(No subfolder name) and last file name must be class name with a semicolon.
5. When you import, does mean that memory is allocated. It just gives the path to reach the file.
6. import com.scientecheasy.state.cityinfo.dhanbad; is always better than import com.scientecheasy.state.cityinfo.*;. 

Final words:
I hope that this article has covered all important topics and tried to understand you in an easy way. 

Next ➝ Methods in Java