Java Math copySign()

The Java Math copySign() method copies the sign of the second argument and assign it to the first argument.

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).