Tuesday, July 31, 2007

STATIC Import, A new feature in JAVA 5.0

Static Import statement is the new addition in JDK 5.0. This statement is used to import the static variables/fields and static members of some class.

Let's take an example, like if we need to use the "PI" static field of Math class in java.lang then we need to write something like :

double a=10;
double res = Math.sin(Math.PI * a);

But if you use the static import in your program then it will be like:

import static java.lang.Math.PI;

double a=10;
double res = Math.sin(PI * a);
you noticed that we have no need to write the fully qualified name of the PI but still we need to write the fully qualified name of the static method "sin" like Math.sin(..).

There is a second form of the static import that imports all of the static fields and members of a class .i.e by using the * notation.


import static java.lang.Math.*;

double a=10;
double res = sin(PI * a);

No comments: