Sunday, 12 April 2015

Static Import


The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.

Advantage of static import:

  • Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:

  • If you overuse the static import feature, it makes the program unreadable and unmaintainable.

Simple Example of static import

  1. import static java.lang.System.*;    
  2. class StaticImportExample{  
  3.   public static void main(String args[]){  
  4.      
  5.    out.println("Hello");//Now no need of System.out  
  6.    out.println("Java");  
  7.   
  8.  }   
  9. }  
  10.       

Output:Hello
       Java
  

What is the difference between import and static import?

The import allows the java programmer to access classes of a package without package qualification whereas the static import feature allows to access the static members of a class without the class qualification. The import provides accessibility to classes and interface whereas static import provides accessibility to static members of the class.

Package class


The package class provides methods to get information about the specification and implementation of a package. It provides methods such as getName(), getImplementationTitle(), getImplementationVendor(), getImplementationVersion() etc.

Example of Package class

In this example, we are printing the details of java.lang package by invoking the methods of package class.




  1. class PackageInfo{  
  2. public static void main(String args[]){  
  3.    
  4. Package p=Package.getPackage("java.lang");  
  5.   
  6. System.out.println("package name: "+p.getName());  
  7.   
  8. System.out.println("Specification Title: "+p.getSpecificationTitle());  
  9. System.out.println("Specification Vendor: "+p.getSpecificationVendor());  
  10. System.out.println("Specification Version: "+p.getSpecificationVersion());  
  11.   
  12. System.out.println("Implementaion Title: "+p.getImplementationTitle());  
  13. System.out.println("Implementation Vendor: "+p.getImplementationVendor());  
  14. System.out.println("Implementation Version: "+p.getImplementationVersion());  
  15. System.out.println("Is sealed: "+p.isSealed());  
  16.   
  17.   
  18.  }  
  19. }  
Output:package name: java.lang
       Specification Title: Java Plateform API Specification
       Specification Vendor: Sun Microsystems, Inc.
       Specification Version: 1.6
       Implemenation Title: Java Runtime Environment
       Implemenation Vendor: Sun Microsystems, Inc.
       Implemenation Version: 1.6.0_30
       IS sealed: false