Java Program: Checking Whether a Number is Positive or Negative
Java, as a versatile programming language, provides a straightforward way to check whether a number is positive or negative. In this comprehensive blog post, we’ll create a Java program to perform this check, offering both an explanation and a step-by-step guide. Additionally, we’ll provide example code with outputs.
Understanding the Concept
A number is considered positive if it is greater than zero and negative if it is less than zero. The concept is fundamental in programming, particularly in scenarios where conditional logic is applied based on the sign of a numeric value.
Java Program to Check Number Sign
Let’s proceed with the Java program. The example includes a method that takes a number as input and determines whether it is positive, negative, or zero.
import java.util.Scanner;
public class CheckNumberSign {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
checkSign(number);
}
// Method to check the sign of a number
static void checkSign(double num) {
if (num > 0) {
System.out.println(num + " is a positive number.");
} else if (num < 0) {
System.out.println(num + " is a negative number.");
} else {
System.out.println("The number is zero.");
}
}
}
Example Usage
Compile the Java program:
javac CheckNumberSign.java
2. Run the compiled program:
java CheckNumberSign
Enter a number when prompted. The program will then determine if it’s positive, negative, or zero.
Example Outputs
Positive Number:
Enter a number: 7.5
7.5 is a positive number.
Negative Number:
Enter a number: -3
-3.0 is a negative number.
Zero:
Enter a number: 0
The number is zero.
Step-by-Step Explanation
User Input:
- The program uses
Scanner
to obtain user input for a numeric value.
- The program uses
Method
checkSign()
:- This method takes a
double
parameter (num
) and checks its sign. - If
num > 0
, it prints that the number is positive. - If
num < 0
, it prints that the number is negative. - If neither condition is met, it prints that the number is zero.
- This method takes a
Conclusion
This Java program demonstrates a fundamental concept in programming—checking whether a number is positive, negative, or zero. The ability to perform such checks is crucial in real-world applications, where decision-making based on numeric values is a common scenario. As you delve into Java programming, mastering these basic constructs is essential for building more complex and functional applications.