In this article we will see what are 'Java packages and Import statement in Java', and how to use Java packages with example.

Java Package

Java packages are folders where Classes, Interfaces and Enums are created to avoid name conflicts and to keep same type of classes, interfaces Enums in same place.

Java packages provides simplicity by providing a structured approach to manage files. Packages can also be used to manage and restrict access to a set of files.

Built-in Package in Java

JDK comes with a number of files, these files are stored and manages in build in packages, as java.util and java.io.

User-defined-package

User defined packages are the packages created to keep application files, these packages can be created in a hierarchical order, a package is physically a folder which can be created in other packages.

Packages can be created by putting the 'package' statement on the top of source file, package declaration is always the very first statement of the file.
package com.tb.demo;

public class Main {
	
}
The above statement will create three folders with name com, tb and demo, demo inside tb and tb inside com.

All classes of the package which we wish to access outside the package must be declared public. All classes within the package must have the package statement as its first line. All classes of the package must be compiled before use (So that they are error free)

'import' keyword in Java

import keyword is used to import built-in and user-defined packages into your java source file so that your class can refer to a class that is in another package by directly using its name.

Case 1 : Importing all the files inside a package

To import all the files inside a package following statement can be created:
import com.tb.*
Here (*) indicates, all the source files inside com/tb folder will be imported, this is not a good practice to import all the files for the sake of using only a few files present in that package.

Case 2 : Importing a specific file only

To import a specific file in a source file following statement is used:
import com.tb.demo
Here only demo.java file will be imported out of all the files present in com/tb folder.

When a package name is not specified, the classes are defined into the default package (the current working directory) and the package itself is given no name.

'package' statement should be very first statement in the file, and after that import statement follows.
package com.tb.demo;
import java.util.List;

public class Main {
	
}
In this article we have seen what are 'Java packages and Import statement in Java', and how to use them with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java