New static methods in JDk6 Part-1

I have been watching the different math methods that are newly released in JDK6. I had found that JDK6 add more static methods. For each given method, there is float method (i.e. if there is “double copySign(double magnitude, double sign)” then there is “float copySign(float magnitude, float sign)” too).

Among all, I have observe process of the Math.copySign() method. Math.copySign()  method sets the sign of the second argument to the sign of first argument. (i.e. (sign of b) + a => c)

Example goes like this:

class CopySignDemo
{
    public static void main(String str[])
    {
        int a=10,b=-1;
        double c = Math.copySign(a,b);
        System.out.println(“(sign of b) + a => c => ” + c);
    }
}

Out Put:
(sign of b) + a => c => -10.0

But rather I found that, this can be easily replaced by a function. Whatever the Math.copySign() is doing in above function, we can create a local function for same purpose.

So, Example goes like this:

class CopySignDemo
{
    public static void main(String str[])
    {
        int a=10,b=-1;
        double c = copySign(a,b);
        System.out.println(“(sign of b) + a => c => ” + c);
    }
    public static double copySign(double magnitude, double sign) {
        if (magnitude == 0.0) return 0.0;
        else if (sign < 0) {
          if (magnitude < 0) return magnitude;
          else return -magnitude;
        }     
        else if (sign > 0) {
          if (magnitude < 0) return -magnitude;
          else return magnitude;
        }
        return magnitude;
    }
}

 

Output:
(sign of b) + a => c => -10.0

Advertisements

One Response to New static methods in JDk6 Part-1

  1. internet says:

    What revealing blog post

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: