Positive Or Negative in Java
Check if a Number is Positive or Negative in Java
In Java, you can easily check whether a given number is positive, negative, or zero by using simple if-else statements.
Here is an example:
Example: Check if a Number is Positive, Negative, or Zero
import java.util.Scanner;public class PositiveNegativeZero { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Asking for user input System.out.print("Enter a number: "); int number = scanner.nextInt(); // Checking if the number is positive, negative, or zero 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."); } scanner.close(); }}Explanation:
if (number > 0): This checks if the number is positive.else if (number < 0): This checks if the number is negative.else: This block is executed if the number is neither positive nor negative, which means it must be zero.
Sample Output:
When the input is positive:
Enter a number: 55 is positive.When the input is negative:
Enter a number: -3-3 is negative.When the input is zero:
Enter a number: 00 is zero.
Shorter Version (Using Ternary Operator)
You can also use a ternary operator for a more concise version:
import java.util.Scanner;public class PositiveNegativeZero { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Asking for user input System.out.print("Enter a number: "); int number = scanner.nextInt(); // Using ternary operator String result = (number > 0) ? "positive" : (number < 0) ? "negative" : "zero"; System.out.println(number + " is " + result); scanner.close(); }}This uses the ternary operator to directly assign the result based on the conditions.
Conclusion
This is a simple and effective way to check if a number is positive, negative, or zero in Java. You can also modify this logic to handle floating-point numbers (like float or double) instead of integers, with the same approach.
Let me know if you'd like any further clarification or additional examples!