Java Math signum()

signum() returns signum function of the argument.

signum() method returns

  • 0.0 if the argument is 0.0.
  • -1.0 if the argument is less than 0.0.
  • 1.0 if the argument is greater than 0.0.

Following is the syntax of signum() method.

</>
Copy
double result = signum(double a)

Since the definition of signum() function has double datatype as argument, you can pass int, float or long as arguments; because these datatypes could implicitly promote to double.

We shall learn about some of the special cases for signum() method with examples.

Example 1 – Math.signum(double)

In the following example, we use signum() method to find the signum function applied on a double value.

Java Program

</>
Copy
public class MathExample {
	public static void main(String[] args) {
		double a = 2.12;
		double result = Math.signum(a);
		System.out.println(result);
	}
}

Output

1.0

Example 2 – Math.signum()

In the following example, we pass an int value as argument to signum() method.

Java Program

</>
Copy
public class MathExample {
	public static void main(String[] args) {
		int a = 25;
		double result = Math.signum(a);
		System.out.println(result);
	}
}

Output

1.0

Example 3 – Math.signum(NaN)

If the argument to signum() is NaN, signum() returns NaN.

Java Program

</>
Copy
public class MathExample {
	public static void main(String[] args) {
		double a = Double.NaN;
		double result = Math.signum(a);
		System.out.println(result);
	}
}

Output

NaN

Example 4 – Math.signum() – Argument is Positive Infinity

If the argument to signum() is Positive infinity, signum() returns 1.0, since positive infinity is greater than 0.0.

Java Program

</>
Copy
public class MathExample {
	public static void main(String[] args) {
		double a = Double.POSITIVE_INFINITY;
		double result = Math.signum(a);
		System.out.println(result);
	}
}

Output

1.0

Example 5 – Math.signum() – Argument is Negative Infinity

If the argument to signum() is Negative infinity, signum() returns -1.0, since negative infinity is less than 0.0.

Java Program

</>
Copy
public class MathExample {
	public static void main(String[] args) {
		double a = Double.NEGATIVE_INFINITY;
		double result = Math.signum(a);
		System.out.println(result);
	}
}

Output

-1.0

Conclusion

In this Java Tutorial, we learned about Java Math.signum() function, with example programs.