Sunday, 2 February 2014

Packages in Java or what is a package?



DEFINITION :

In java, package is a set of classes, interfaces , enumerations etc which are grouped together.

Every class is definitely attached with some package.

MOSTLY USED PACKAGES IN JAVA :

java.lang : Basically provides classes related to printing and scanning.
java.io : provides classes related to input and output.
java.util : provides classes related to date and time.
java.awt : provides classes like Applet, Frame etc and used in applet programming.

To use the package classes, it should be imported with the use of import statement.
You can make your own package, define your own class in that and than you can use
that package and its classes in another package by importing.
These Java packages can be stored in compressed files called JAR files.

Note :

java.lang package is imported in every java program by default, you don't have a need 
to import that package in your program but if you want to use some input and output in your program than there is a need to import the java.io package.

How to declare a package?

Syntax:
package<space><package-name>;
e.g
 package myPackage;  

It should be the first statement in any java program.

How to import a package?
Syntax:
import<space><package-name><.><* or name of class you want to use from that package>;

e.g.
1. To import the class MyClass from myPackage
 import myPackage.MyClass;  

2. To import all classes from myPackage
 import myPackage.*;  

It should be declared after the package declaration outside the class.
Also, according to the code convention the package name should be used in small characters.

EXAMPLE :

1:  package abc;  
2:  import java.util.Date;  
3:    
4:  public class MyClass  
5:  {  
6:       //create a method which we will use in another package.  
7:       public void myMethod()  
8:       {  
9:            System.out.println("This is a different package.");  
10:              
11:            //to print the current date and time.  
12:            Date date = new Date();  
13:              
14:            //without importing the java.util.Date we cannot use the Date class.  
15:            System.out.println(date.toString());  
16:       }  
17:  }  



In another package we can use myMethod() as

1:  package xyz;  
2:  //import the abc package so that you can use the method.  
3:  import abc.MyClass;  
4:    
5:  class DemoPackage  
6:  {  
7:       public static void main(String[] args)  
8:       {  
9:            MyClass obj = new MyClass();  
10:            obj.myMethod();  
11:       }  
12:  }  
Read more