wellnwill Marathahalli Bangalore

Package

A package is like a container that contain collection of related classes, interfaces, enums, annotations and sub packages. We use package keyword to declare a package.

Syntax:

package package_name;
Ex:- package p1;

Advantage of package:

  • Packages are used to avoid naming conflicts.
  • Packages provide control access of class, interface and enumeration etc. (i.e. security).
  • It improves modularity of the application i.e. we can break an application into sub modules and locate the related classes.

Type of Packages:

  • Predefined packages
  • User defined packages

Predefined packages:

These packages are developed by Sun micro systems and other java vendors to simplify the task of java programmer.

Ex- java.lang, java.io, java.awt, java.net, java.sql, java.util etc.

User defined packages:

These packages are developed by users (programmers) based on the application requirements.

Developing a user defined package

                                                      
class Test175
{  
    public static void main(String args[])
	{	
    System.out.println("program without user defined package");
    }
}    

Step to compile the program without developing package.

Syntax- javac .java
Ex-     javac Test175.java

Step to run the program without developing package

Syntax- java 
Ex-     java Test175
                                                    
package pack1;
class Test176
{  
    public static void main(String args[]){	
    System.out.println("with user defined package");
    }
}    

Step to compile the program with user defined package

Syntax- javac  -d   .java
Ex-     javac –d . Test176.java 

(after compilation pack1 folder will be created inside current directory and Test176.class file will be saved under pack1 folder).

Step to run the program with user defined package

Syntax- java .
Ex-     java pack1.Test176

  • When we write class without creating package then generated class will be placed in current working directory.
  • When we write class with creating package then generated class will be placed specified package.
  • If specified package structure is not available then JVM itself creates corresponding package structure.

Step to compile the program with user defined package

Syntax

javac -d .java

In the above compilation statement path can be replaced with . (dot) or any directory name. The -d is an option or switch which gives an indication to JVM for the destination where to put the generated class file.

Case 1:

if we use (dot) . then package will be created in the current working directory and generated .class file will be placed in that package.

Case 2:

if we want to create the package in specified directory then you have to specify the location and generated .class file will be placed in corresponding package structure.

Footer with Map

Top