Write a Java program to Find the sign of given number using library method


This Java program reads a double value from the user and then uses the Math.signum method to determine the sign of the number. Here's a breakdown of the program:

  • The import java.util.*; statement imports the java.util package, which contains the Scanner class that is used to read input from the user.
  • The public class FindSign_GivenNumber statement declares a public class called FindSign_GivenNumber, which is the name of the Java file that this program is saved in.
  • The public static void main(String[] args) method is the entry point for the program. It takes an array of strings as an argument, but in this program, that argument is not used.
  • Inside the main method, a new Scanner object called input is created to read input from the user.
  • A double variable num is declared and initialized to 0.
  • The program prompts the user to enter a double value using System.out.print and reads it using input.nextDouble().
  • The Math.signum(num) method is used to determine the sign of num. This method returns -1.0 if the number is negative, 0.0 if the number is zero, and 1.0 if the number is positive.
  • An if-else statement is used to check the result of Math.signum(num) and print the appropriate message to the console.

Source Code

import java.util.*;
public class FindSign_GivenNumber
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		double num = 0;
 
		System.out.print("Enter The Number : ");
		num = input.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 The Number : 91
Number is Positive

Example Programs