Skip to main content

Java Packages

Package are used to grouping of classes, interfaces and sub packages. That is very useful mechanism to arrange well code structures under the protection. Package is like a namespace which are resolve ambiguity of scopes. Because there can be possible exist similar name classes in two different package.

Define custom package

package packageName;

package name start with lowercase character.

package testpack;  
public class Test{ 
 //main method of this package 
 public static void main(String args[]){  
    System.out.println("Test Package");  

//javac -d .

//java testpack.Test
Test Package

When compiling this source code, that is create a subfolder on root application that name is testpack and inside this folder would have Test.class file.

Use package

import keyword are used to utilize the custom or inbuilt package in java source code file. this statement are normally defines at top of the source code.

package sets;  
public class Record{ 
  //Method of Record class
  public void test(){
    System.out.println("Start Test");
  public void operation(){
    System.out.println("Start Operation");

//javac -d .
//Import package class
import sets.Record;
class Student{
    public static void main(String[] args) {
    Record obj = new Record();

//run  java Student
Start Test
Start Operation

Import an entire package

There are possible to import an entire package using an * asterisk.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment