Java Program to Check if a Number is Positive or Negative β With Examples
Introduction
Checking whether a number is positive, negative, or zero is one of the most fundamental operations in Java. Itβs useful in many real-world applications such as data validation, financial analysis, and control systems.
By the end of this tutorial, you’ll know how to:
- Identify if a number is positive, negative, or zero
- Take user input using
Scanner - Use clean
if...elsebranching
Rule: Positive, Negative, or Zero
- A number is positive if
number > 0 - Negative if
number < 0 - Zero if
number == 0
Java Program β Hardcoded Number
public class PositiveNegativeCheck {
public static void main(String[] args) {
int number = -15;
if (number > 0) {
System.out.println(number + " is positive.");
} else if (number < 0) {
System.out.println(number + " is negative.");
} else {
System.out.println("The number is zero.");
}
}
}
Explanation:
- Basic
if...else if...elselogic. - Checks if the number is greater, less than, or equal to zero.
Java Program β User Input with Scanner
import java.util.Scanner;
public class PositiveNegativeInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
if (number > 0) {
System.out.println(number + " is positive.");
} else if (number < 0) {
System.out.println(number + " is negative.");
} else {
System.out.println("The number is zero.");
}
scanner.close();
}
}
Works for both integers and decimals.
Java Method β Reusable Function
public class SignChecker {
public static String checkSign(double num) {
if (num > 0) return "Positive";
else if (num < 0) return "Negative";
else return "Zero";
}
public static void main(String[] args) {
double number = 0.0;
System.out.println(number + " is " + checkSign(number));
}
}
Ideal for use in larger programs or modular codebases.
Sample Output
Enter a number: -3.5
-3.5 is negative.
Enter a number: 0
The number is zero.
Enter a number: 12
12.0 is positive.
Summary
In this article, youβve learned:
- How to check if a number is positive, negative, or zero
- Use of
if...elsebranching in Java - Input handling with
Scannerand method reuse
This logic is foundational for data analysis, logic design, and control flow programming.
FAQ β Java Positive or Negative Check
Does this work for decimal numbers?
Yes, the code supports both int and double.
How can I skip checking for zero?
Remove the else condition and only check > 0 and < 0.
What happens if I enter non-numeric input?
You’ll get an InputMismatchException. Wrap the input in a try-catch block for better error handling.
Share Now :
