Open In App

Java Math copySign() Method

Last Updated : 12 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The copySign() method in Java is a part of java.lang.Math class. This method copies the sign of one number to the magnitude of another. We can also say that it takes two numbers and returns a value with the absolute value of the first and the sign of the second.

This method is very useful in mathematical computations where controlling the sign of values is important. This method controls over the sign of a number without changing its absolute value.

Syntax of copySign() Method

This method comes in two forms:

public static double copySign(double magnitude, double sign)

public static float copySign(float magnitude, float sign)

Parameters:

  • magnitude: The number whose absolute value will be used.
  • sign: The number whose sign (+ or -) will be applied to the result.

Return Value:

The method returns a new value that has:

  • The magnitude of the first argument.
  • The sign of the second argument.

Why Use Math.copySign() Method?

  • We should use this method to control the direction of a value while preserving the magnitude.
  • To avoid manually using conditional checks like if-else for assigning sign.

Working of copySign() Method

  • If both numbers are positive, then the result is positive.
  • If magnitude is positive and sign is negative, then the result is negative.
  • If magnitude is negative and sign is positive, then the result is positive.
  • If both are negative then the result is negative.

Examples of Java Math copySign() Method

Example 1: In this example, we will take double inputs where one value is positive and the other value is negative.

Java
// Using double values with Math.copySign()
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        double a = 34.543;
        double b = -123.44;

        System.out.println("Result 1: " + Math.copySign(a, b)); 
        System.out.println("Result 2: " + Math.copySign(b, a)); 
    }
}

Output
Result 1: -34.543
Result 2: 123.44


Example 2: In this example, we will use float values and apply the sign of a negative number to a positive float value.

Java
// Using float values with Math.copySign()
import java.lang.Math;

public class Geeks {
    
    public static void main(String[] args) {
        float a = 87.56f;
        float b = -685.23f;

        System.out.println("Result 1: " + Math.copySign(a, b)); 
        System.out.println("Result 2: " + Math.copySign(b, a)); 
    }
}

Output
Result 1: -87.56
Result 2: 685.23

Explore