Examples
- Leap Year Program in Java (Check Leap Year or Not)
- Check Number is Positive or Negative in Java (4 Ways)
- Java Program to Check Character is Alphabet or Not
- Armstrong Number Program in Java (for loop, Recursion)
- Print Prime Numbers Between 1 to N in Java (1 to 100)
- Java Program for Palindrome Number (Palindrome Code)
- Sum of n Natural Numbers in Java (Programs & Explanation)
- Java Multiplication Table Program (Loops, 2D Array) 5 Ways
- Find GCD of Two Numbers in Java (HCF Program)
- GCD of Three Numbers in Java (HCF of 3 Numbers Program
- GCD of Array in Java (GCD of n Numbers Program)
- LCM of Two Numbers in Java (LCM Program and Code)
- LCM of Three Numbers in Java (Easy Programs)
- LCM of n Numbers in Java (LCM of Array of Numbers)
- How to Print A to Z in Java? 3 Ways to Print Alphabets
Check Number is Positive or Negative in Java (4 Ways)
In programming, one of the fundamental tasks often encountered is the need to check whether a number is positive or negative. This seemingly simple task serves as a foundational building block in many real-world applications. Whether you are developing financial software to track profits and losses, creating games that involve scorekeeping, or even building scientific simulations, the ability to classify numbers as positive or negative is a crucial skill.
This tutorial will guide you through the process of writing a Java program to check whether a number is positive, negative, or zero (0). We will cover the underlying logic and provide you with step-by-step instructions to implement this functionality in your Java projects.
Uses of These Programs
Here are some meaningful use cases for such programs:
-
Financial Applications: In banking and accounting software, you often need to calculate and display account balances. Identifying whether a transaction is a credit or debit, i.e., positive or negative, is vital for accurate bookkeeping.
-
Game Development: Games often involve scoring and keeping track of player performance. Detecting whether a player has gained points (positive) or lost points (negative) helps maintain scoreboards and determine game outcomes.
-
Mathematical Calculations: When working on mathematical algorithms or scientific simulations, knowing the sign of a number can be crucial for correct mathematical operations and simulations.
-
Input Validation: Validating user input is an essential part of building robust software. Checking the sign of input numbers can help prevent unintended errors and ensure that your program receives valid data.
-
Error Handling: In error-handling scenarios, such as exception handling, you may need to determine whether an error code or value is positive (indicating success) or negative (indicating an error).
So, let's dive in and get started with building this valuable piece of functionality in Java!
Concepts to Learn:
Check Number is Positive or Negative in Java Using if
This program uses a straightforward if statement to determine whether the input number is positive, negative, or zero and provides a clear output based on the condition met.
Here's a Java program to check whether a number is positive or negative using an if statement
Code
import java.util.Scanner;
public class PositiveNegativeChecker {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
// Check if the number is positive or negative using an if statement
if (number > 0) {
System.out.println("The number " + number + " is positive.");
} else if (number < 0) {
System.out.println("The number " + number + " is negative.");
} else {
System.out.println("The number is zero.");
}
// Close the scanner to free up resources
scanner.close();
}
}
Output
Enter a number: 7.5
The number 7.5 is positive.
Explanation
-
We import the java.util.Scanner class to read user input.
-
We create a Scanner object named scanner to take user input.
-
The user is prompted to enter a number, and the input is stored in the number variable.
-
We use an if statement to check whether the number is greater than zero. If it is, we print that the number is positive.
-
If the number is less than zero, we print that it is negative.
-
If neither condition is met, it means the number is zero, so we print that.
-
Finally, we close the Scanner to free up resources.
Check Number is Positive, Negative, Zero Using Ternary Operator
This program uses the ternary operator to provide a more concise way of checking whether the input number is positive, negative, or zero and gives an appropriate output based on the condition met.
Here's a Java program to check whether a number is positive or negative using the ternary operator (? :):
Code
import java.util.Scanner;
public class PositiveNegativeChecker {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
// Use the ternary operator to check if the number is positive or negative
String result = (number > 0) ? "positive" : (number < 0) ? "negative" : "zero";
// Display the result
System.out.println("The number " + number + " is " + result + ".");
// Close the scanner to free up resources
scanner.close();
}
}
Output
Enter a number: -3.2
The number -3.2 is negative.
Explanation
-
We import the java.util.Scanner class to read user input.
-
We create a Scanner object named scanner to take user input.
-
The user is prompted to enter a number, and the input is stored in the number variable.
-
We use the ternary operator ? : to check whether the number is greater than zero. If it is, the result is set to "positive"; otherwise, we check if it's less than zero, and if so, the result is set to "negative." If neither condition is met, it means the number is zero, so we set the result to "zero."
-
We display the result, incorporating it into the output message.
-
Finally, we close the Scanner to free up resources.
Check Number is Positive or Negative Using Math.signum()
Here's a Java program to check whether a number is positive or negative using the Math.signum() method:
Code
import java.util.Scanner;
public class PositiveNegativeChecker {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
// Use the Math.signum() method to check if the number is positive or negative
double sign = Math.signum(number);
String result = (sign > 0) ? "positive" : (sign < 0) ? "negative" : "zero";
// Display the result
System.out.println("The number " + number + " is " + result + ".");
// Close the scanner to free up resources
scanner.close();
}
}
Output
Enter a number: 0.0
The number 0.0 is zero.
Explanation
-
We import the java.util.Scanner class to read user input.
-
We create a Scanner object named scanner to take user input.
-
The user is prompted to enter a number, and the input is stored in the number variable.
-
We use the Math.signum() method to determine the sign of the number. This method returns -1.0 for negative numbers, 1.0 for positive numbers, and 0.0 for zero.
-
We use the value returned by Math.signum() in a ternary operator ? : to set the result variable to "positive," "negative," or "zero" based on the sign of the number.
-
We display the result, incorporating it into the output message.
Check Number is Positive or Negative Using Bitwise Operator
Here's a Java program to check whether a number is positive or negative using bitwise operators:
Code
import java.util.Scanner;
public class PositiveNegativeChecker {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
// Use bitwise operators to check if the number is positive or negative
boolean isPositive = (Double.doubleToRawLongBits(number) & Long.MIN_VALUE) == 0;
// Display the result
if (isPositive) {
System.out.println("The number " + number + " is positive.");
} else {
System.out.println("The number " + number + " is negative.");
}
// Close the scanner to free up resources
scanner.close();
}
}
Output
Enter a number: -8.9
The number -8.9 is negative.
Explanation
-
We import the java.util.Scanner class to read user input.
-
We create a Scanner object named scanner to take user input.
-
The user is prompted to enter a number, and the input is stored in the number variable.
-
We use Java bitwise operators to check if the number is positive or negative. Specifically, we use Double.doubleToRawLongBits(number) to convert the number into its raw long bit representation and then perform a bitwise AND operation with Long.MIN_VALUE. If the result is 0, the number is considered positive; otherwise, it's considered negative.
-
We display the result using an if statement, indicating whether the number is positive or negative.
-
Finally, we close the Scanner to free up resources.
Learn Next: