Check if a Number is Positive or Negative in Java
Given an integer input, the objective is to write a code to Check if a Number is Positive or Negative in Java Language.
Example
Input: Num = -5
Output: The number is Negative
Methods to Check Number Sign
Given an integer input, the objective is to check whether the given integer is Positive or Negative. In order to do so we have the following methods:
-
Method 1: Using Brute Force
Algorithm
For a user input num:
If the num > 0: it is a positive number.
If the num < 0: it is a negative number.
Else the number has to be zero itself
import java.util.Scanner; public class PositiveNegative { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); if (num > 0) { System.out.println("The number is Positive"); } else if (num < 0) { System.out.println("The number is Negative"); } else { System.out.println("The number is Zero"); } sc.close(); } }
Output:
Enter a number: -5 The number is Negative
-
Method 2: Using Nested if-else Statements
Algorithm
1. Take input from the user
2. If the number is greater than zero, print "Positive"
3. Else, check if the number is less than zero
4. If true, print "Negative"
5. Otherwise, print "Zero"
import java.util.Scanner; public class NestedIf { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); if (num >= 0) { if (num == 0) System.out.println("The number is Zero"); else System.out.println("The number is Positive"); } else { System.out.println("The number is Negative"); } sc.close(); } }
Output:
Enter a number: 0 The number is Zero
-
Method 3: Using the ternary operator
Algorithm
1. Take input from the user
2. Use the ternary operator to check the number's sign
3. Print the result accordingly
import java.util.Scanner; public class TernaryOperator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); String result = (num > 0) ? "The number is Positive" : (num < 0) ? "The number is Negative" : "The number is Zero"; System.out.println(result); sc.close(); } }
Output:
Enter a number: 10 The number is Positive