โโ 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...else
branching
๐งฎ 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...else
logic. - 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...else
branching in Java - โ
Input handling with
Scanner
and 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 :