Packages in Java

According to functionality Java API provides a large number of cases grouped into different packages. In our programming development we use many predefined classes in our program and to do so we import these classes in our program because they are in different packages.

Packages in Java, Packages in Java with Example Program

Here in this hierarchy, we can see java has many inbuilt packages that we use in daily programming.

Using Packages in Java

  • We use the String class which is present in java.lang package. To use String class we don’t need to write an import statement, because java by default adds all the classes of the java.lang package in all the programs.

  • We use the Properties class which is present in java. util package. To use this class we have to write an import statement because this is in a different package. import java.util.Properties;

  • We use File class which is present in the java.io package. To use file class we have to write an import statement. import java.io.File;

There are two ways to access a different package class in our program-

  • First is a fully qualified name as we see in the above statements. import java.io.File;

  • Second is giving the super package name and including all the sub packages and subclasses import java.io.*;

Creating Packages in Java

To create our class in a package we must declare this class inside the package declaration. To do this we must declare the package name first by using the package keyword followed by package name. Package declaration is must be the first statement in our java source program file.

Here is an example-

package packagename; // package declaration

public class ClassName { // class declration

	..... // body of our class
	
}

Accessing Packages in Java

A package or a class present in an outside package can be easily accessed in our program by import statement. The definition of a class that we are using in the program must be known by our program structure and that’s why we have to include this class in our program in this way – import packagename.ClassName;

Example:

Here below program, reading a file and printing content of the file on the console.

To use File class and FileReader class we have to write an import statement, here we are importing these classes from java.util package.

package packagename; // package declaration

import java.io.BufferedReader; // importing package
import java.io.File; // importing File class
import java.io.FileReader; // importing FileReader class

public class ClassName { // class declration

	public static void main(String[] args) {

		File file = new File("D:\\FileFolder\\filename.txt");

		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader(file));
			String st;
			while ((st = br.readLine()) != null)
				System.out.println(st);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Share