Java - How To Find Positive or Negative Numbers
Determining whether a number is positive, negative, or zero is a fundamental programming exercise. In Java, this can be achieved using simple conditional statements.
How to Determine Positive or Negative Numbers?
Positive Number: A number greater than zero (n > 0).
Negative Number: A number less than zero (n < 0).
Zero: Neither positive nor negative (n == 0).
Java Program Example
Code Example 1: Check Positive or Negative Using if-else
import java.util.Scanner;
public class PositiveNegativeCheck {
public static void main(String[] args) {
// Create a Scanner object for 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, negative, or zero
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
scanner.close();
}
}
Example Output:
Input: 5
Output: The number is positive.
Input: -3.7
Output: The number is negative.
Input: 0
Output: The number is zero.
Code Explanation
Scanner Class: Used to read input from the user.
Conditional Statements:
If number > 0, it is positive.
If number < 0, it is negative.
If neither of the above, it is zero.
Code Example 2: Using a Method
Encapsulate the logic in a reusable method:
public class PositiveNegativeCheck {
public static void main(String[] args) {
checkNumber(15); // Positive
checkNumber(-8); // Negative
checkNumber(0); // Zero
}
// Method to check positive or negative
public static void checkNumber(double number) {
if (number > 0) {
System.out.println(number + " is positive.");
} else if (number < 0) {
System.out.println(number + " is negative.");
} else {
System.out.println(number + " is zero.");
}
}
}
Code Example 3: Using Ternary Operator
You can simplify the logic using a ternary operator:
import java.util.Scanner;
public class PositiveNegativeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
// Ternary operator to determine the result
String result = (number > 0) ? "positive"
: (number < 0) ? "negative"
: "zero";
System.out.println("The number is " + result + ".");
scanner.close();
}
}
Use Cases
Validating user input.
Building calculator programs.
Implementing financial or scientific applications.
Conclusion
This program showcases the simplicity of checking whether a number is positive, negative, or zero in Java. The examples demonstrate multiple approaches — from basic if-else to using methods and ternary operators, making the code more flexible and reusable.