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

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024