HomeJavaJava Program to Check if a Number is Positive or Negative

Java Program to Check if a Number is Positive or Negative

In this Java program, we’ll learn how to Check if a Number is Positive or Negative in Java.   

How to Check if a Number is Positive or Negative in JAVA? 

Example 1: Check if a number is positive or negative using Math.signum() method. 

RUN CODE SNIPPET
import java.util.Scanner;   
import java.lang.Math.*;   
public class Main   
{   
public static void main(String[] args)    
{   
double num, result;      
Scanner sc = new Scanner(System.in);   
System.out.print("Enter a number you want to check: ");     
num = sc.nextDouble();    
result=Math.signum(num);   
System.out.print(result);   
}   
}

OUTPUT 

Enter a number you want to check: 50 
1.0

Java Math class is a static method that accepts a parameter of double type. 

If the argument is 1.0 then the number is >0, else if the argument is –1.0 then the number is <0. 

Example 2: Check if a number is positive or negative using if. Else statement. 

RUN CODE SNIPPET
public class Main  
{ 
    public static void main(String[] args)  
    { 
        double number = -5.0; 
        if (number < 0.0) 
            System.out.println(number + " is a negative number."); 
        else if ( number > 0.0) 
            System.out.println(number + " is a positive number."); 
        else 
            System.out.println(number + " is 0."); 
    } 
}

OUTPUT 

-5.0 is a negative number.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022