×

# Java program to find the sign of given number using library method

Given a number, we have to find the sign of given number using library method.
Submitted by Nidhi, on May 16, 2022

## Problem statement

In this program, we will read a floating-point number from the user using the Scanner class and find the sign of the given number using the Math.signum() method.

The Math.signum() method returns:

• If the argument is zero, it will return Zero.
• If the argument is a positive value, it will return Positive 1.
• If the argument is a Negative value, it will return Negative 1.
• If the argument is NaN, it will return NaN.

## Source Code

The source code to find the sign of a given number using the library method is given below. The given program is compiled and executed successfully.

```// Java program to find the sign of a given number
// using the library method

import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner X = new Scanner(System.in);

double num = 0;

System.out.print("Enter number: ");
num = X.nextDouble();

double res = Math.signum(num);
if (res == 0)
System.out.print("Number is zero.");
else if (res == -1)
System.out.print("Number is negative.");
else if (res == 1)
System.out.print("Number is positive.");
else
System.out.print("Number is NaN.");
}
}
```

### Output

```Enter number: -34
Number is negative
```

## Explanation

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main that contains a main() method.

The main() method is the entry point for the program. Here, we created a variable num of double type and read its value from the user using the nextDouble() method of the Scanner class. Then we found the sign of the given number using the Math.signum() method and printed the appropriate message.