Java Math copySign()

The syntax of the copySign() method is:

Math.copySign(arg1, arg2)

Here, copySign() is a static method. Hence, we are accessing the method using the class name, Math.


copySign() Parameters

The copySign() method takes two parameters.

  • arg1 - first argument whose sign is to be replaced
  • arg2 - second argument whose sign is copied to arg1

Note: The data types of arg1 and arg2 should be either float or double.


copySign() Return Values

  • returns the first argument, arg1 with sign of the second argument, arg2

Note: For arguments (arg1, -arg2), the method returns -arg1.


Example: Java Math.copySign()

class Main {
  public static void main(String[] args) {

    // copy sign of double arguments
    double x = 9.6d;
    double y = -6.45;
    System.out.println(Math.copySign(x, y));  // -9.6

    // copy sign of float arguments
    float a = -4.5f;
    float b = 7.34f;
    System.out.println(Math.copySign(a, b));  // 4.5

  }
}

Here, as you can see the copySign() method assigns the sign of second variables (y and b) to the first variables (x and a).

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges