Wednesday, June 22, 2005

Static imports in J2SE 5.0

Do you hate to type Java code? Static imports helps you save some typing. If you are using a static class or a static variable, you can import them and save some typing. The simple example below, should clarify this concept:
import static java.lang.Math.*;
import static java.lang.System.out;

public class MyMath5
{
public static void main(String[] args)
{
// returns a double between 0.0 thro' (but not
// including) 1.0
double r1 = random();
int r2 = (int) (random() * 5);
out.println("r1 = " + r1);
out.println("r2 = " + r2);

// Returns the absolute value of the argument
int x = abs(-240);
double d = abs(240.45);
out.println("x = " + x);
out.println("d = " + d);

// Returns an int or long (depending on whether
// the argument is foat or double)
// rounded to the nearest integer value
int p = round(-24.8f);
long q = round(24.45);
out.println("p = " + p);
out.println("q = " + q);

// Returns a value that is minimum of two values
int c = min(243, 240);
double dd = min(90876.5, 90876.49);
out.println("c = " + c);
out.println("dd = " + dd);

// Returns a value that is maximum of two values
int e = max(243, 240);
double f = max(90876.5, 90876.49);
out.println("e = " + e);
out.println("f = " + f);
}
}

Technorati Tags: , ,
Blogs linking to this article

0 Comments:

Post a Comment

<< Home