Program To Check If A Number Is Positive Or Negative In Java
Understanding how to determine if a number is positive, negative, or zero is a fundamental concept in programming. In this article, you will learn various Java approaches to check the sign of a given number, from basic conditional statements to more advanced utility methods.
Problem Statement
Many programming tasks require conditional execution based on whether a numerical input is positive, negative, or zero. For instance, an application might need to process financial transactions differently for credits (positive) versus debits (negative), or a game engine might adjust character movement based on directional input signs. The core problem is to reliably classify an integer or floating-point number into one of these three categories.
Example
Consider the number 15. A simple check would determine that 15 is a positive number. If the input were -7, the check should identify it as negative. For 0, it should be classified as zero.
Background & Knowledge Prerequisites
To effectively follow this article, you should have a basic understanding of:
- Java Syntax: How to declare variables, use data types (like
int,double). - Conditional Statements: Familiarity with
if,else if, andelseconstructs. - Input/Output: Using the
java.util.Scannerclass to read user input. - Operators: Basic arithmetic and comparison operators (e.g.,
==,>,<).
For code examples, ensure your Java Development Kit (JDK) is installed and configured. No special libraries are needed beyond standard Java APIs.
Use Cases or Case Studies
Determining the sign of a number is a common requirement across many applications:
- Financial Applications: Validating transaction amounts (e.g., ensuring a withdrawal is negative, a deposit is positive, or preventing zero-value transactions).
- Data Validation: Checking if user input for age, quantity, or score is non-negative.
- Game Development: Adjusting game physics (e.g., applying forces in a positive or negative direction) or checking health points.
- Mathematical Operations: Preventing division by zero or taking the square root of a negative number.
- Control Systems: Monitoring sensor readings to ensure they are within an expected positive range or detecting deviations into negative values.
Solution Approaches
Here are a few common approaches to check if a number is positive or negative in Java.
1. Using if-else if-else Statement
This is the most straightforward and explicit way to check a number's sign.
- Summary: Directly compares the number against zero using standard relational operators.
// Check Number Sign with If-Else
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user to enter a number
System.out.print("Enter a number: ");
double number = scanner.nextDouble(); // Read the number (using double for flexibility)
// Step 3: Check the sign of the number using if-else if-else
if (number > 0) {
System.out.println(number + " is a positive number.");
} else if (number < 0) {
System.out.println(number + " is a negative number.");
} else {
System.out.println(number + " is zero.");
}
// Step 4: Close the scanner
scanner.close();
}
}
- Sample Output:
Enter a number: 10 10.0 is a positive number. Enter a number: -5.5 -5.5 is a negative number. Enter a number: 0 0.0 is zero.
- Stepwise Explanation:
- A
Scannerobject is initialized to read input from the console. - The program prompts the user to enter a number and reads it as a
doubleto handle both integers and floating-point values. - The
ifcondition(number > 0)checks if the number is greater than zero. If true, it's positive. - If the first
ifis false, theelse ifcondition(number < 0)checks if the number is less than zero. If true, it's negative. - If both previous conditions are false, it means the number must be exactly zero, so the final
elseblock is executed. - Finally, the
Scanneris closed to release system resources.
2. Using the Ternary Operator
For a more concise check, especially if the output is a simple string, the ternary operator can be used.
- Summary: A single-line conditional expression that returns one of two values based on a boolean condition.
// Check Number Sign with Ternary Operator
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt and read the number
System.out.print("Enter a number: ");
int number = scanner.nextInt(); // Using int for this example
// Step 3: Use the ternary operator to determine the sign and print
String result = (number > 0) ? "positive" : (number < 0) ? "negative" : "zero";
System.out.println(number + " is " + result + ".");
// Step 4: Close the scanner
scanner.close();
}
}
- Sample Output:
Enter a number: 25 25 is positive. Enter a number: -12 -12 is negative. Enter a number: 0 0 is zero.
- Stepwise Explanation:
- A
Scannerreads an integer input. - The expression
(number > 0) ? "positive"first checks if the number is positive. If true,resultbecomes "positive". - If false, the part after the first colon
(number < 0) ? "negative" : "zero"is evaluated. This is a nested ternary operator. - The nested part checks if
numberis negative. If true,resultbecomes "negative". Otherwise (if not positive and not negative, meaning it's zero),resultbecomes "zero". - The final
resultstring is then printed along with the number. - The
Scanneris closed.
3. Using Integer.signum() or Math.signum()
Java provides utility methods in Integer and Math classes that return the sign of a number as an integer.
- Summary:
Integer.signum()forintandMath.signum()forfloat/doublereturn1for positive,-1for negative, and0for zero.
// Check Number Sign with signum() method
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt and read the number (using int for Integer.signum())
System.out.print("Enter an integer: ");
int intNumber = scanner.nextInt();
// Step 3: Get the sign using Integer.signum()
int intSign = Integer.signum(intNumber);
// Step 4: Print the result based on the sign
if (intSign == 1) {
System.out.println(intNumber + " is a positive number (using Integer.signum()).");
} else if (intSign == -1) {
System.out.println(intNumber + " is a negative number (using Integer.signum()).");
} else {
System.out.println(intNumber + " is zero (using Integer.signum()).");
}
// Step 5: Prompt and read a double (for Math.signum())
System.out.print("Enter a floating-point number: ");
double doubleNumber = scanner.nextDouble();
// Step 6: Get the sign using Math.signum()
double doubleSign = Math.signum(doubleNumber); // Returns 1.0, -1.0, or 0.0
// Step 7: Print the result based on the sign
if (doubleSign == 1.0) {
System.out.println(doubleNumber + " is a positive number (using Math.signum()).");
} else if (doubleSign == -1.0) {
System.out.println(doubleNumber + " is a negative number (using Math.signum()).");
} else {
System.out.println(doubleNumber + " is zero (using Math.signum()).");
}
// Step 8: Close the scanner
scanner.close();
}
}
- Sample Output:
Enter an integer: 42 42 is a positive number (using Integer.signum()). Enter a floating-point number: -3.14 -3.14 is a negative number (using Math.signum()).
- Stepwise Explanation:
- The program reads an
intand adoublefrom the user. Integer.signum(intNumber)is called for the integer. It returns1for positive,-1for negative, and0for zero.- An
if-else if-elseblock then interprets thisintSignto print the appropriate message. - Similarly,
Math.signum(doubleNumber)is called for the double. It returns1.0,-1.0, or0.0. - Another
if-else if-elseblock interprets thedoubleSignfor floating-point numbers. - The
Scanneris closed. - Note that
Math.signum()can be used for bothfloatanddoublearguments.Integer.signum()is specific toint. There are alsoLong.signum()andByte.signum().
Conclusion
Checking if a number is positive, negative, or zero is a foundational programming task with multiple practical solutions in Java. While the if-else if-else statement offers clarity and explicit control, the ternary operator provides a more compact syntax for simple assignments. For a generalized approach, Integer.signum() and Math.signum() methods offer a clean and efficient way to retrieve the sign value directly. The choice of method often depends on readability preference, conciseness, and the specific data type being handled.
Summary
- Basic Comparison: Use
number > 0,number < 0, andnumber == 0withif-else if-elsefor clear, explicit checks. - Concise Logic: The ternary operator (
condition ? value_if_true : value_if_false) offers a compact way to assign results based on sign. - Utility Methods:
Integer.signum(int)andMath.signum(double)provide built-in functions that return1(positive),-1(negative), or0(zero) for convenience. - Data Types: Be mindful of using
intforInteger.signum()andfloatordoubleforMath.signum(). - Readability: Choose the approach that best balances clarity and efficiency for your specific use case.