Written by Sai Sandeep Thota on August 9, 2013 in Java > Programming

What are Packages in Java?


Get our Latest updates delivered to your mailbox!

Package is a Java’s way of grouping classes, interfaces together. The grouping is usually done according to the functionality. There are two types of Packages. They are: User-defined and Pre-defined packages.

Package act as container for classes. The benefits of packages are like:

  1. Classes contained in the packages of other programs can be easily re-used.
  2. In packages, classes can be unique compared with classes in other packages. i.e., two classes can have same name. They may be referred by their fully qualified name.
  3. Packages provide a way to hide classes, thus preventing other programs or packages from accessing classes that are meant for internal use only.

Some of the most commonly used Java packages are java.lang, java.util, java.io, java.awt, java.net, java.applet etc.,

Example of a Package program in Java

We are going to perform addition of two numbers using Packages. We will need two files, one is for package and other is the actual program .

The below is the package file named calculate.java. A package file is same as a normal java program but you will need to define the class in public and package keyword followed by package name in the beginning of the program.

package Sum;

public class calculate {
	public void add(int x, int y)
		System.out.println("Sum of "+x+" and "+y+" is: "+(x+y));

The below is the program which imports the above package. Packages are placed in a separate folder(folder is named with respective package name). In this program, we are having the package named Sum, so we have created a folder called Sum and placed our calculate.java in the Sum folder as it belongs to Sum package. Then going back to the parent directory we are creating a file named addNumbers.java which imports Sum.calculate, that means it is importing calculate class of Sum package. Take a look at the screenshot, you will get a clear idea. You can also download the source code attached below.

import Sum.calculate;
import java.util.Scanner;

class addNumbers {
	public static void main(String args[])
		int a,b;
		Scanner get = new Scanner(System.in);
		System.out.println("Enter two Numbers:");
		a = get.nextInt();
		b = get.nextInt();
		calculate ob = new calculate();

Download Source Code


{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: