Positive or Negative Number in Java

Check whether a number is positive, negative, or zero.

BeginnerModule 1: Basic Java ProgramsExample 8 of 20
positive-or-negative-number.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter a number: ");
8 double n = sc.nextDouble();
9
10 if (n > 0) {
11 System.out.println(n + " is Positive");
12 } else if (n < 0) {
13 System.out.println(n + " is Negative");
14 } else {
15 System.out.println("Number is Zero");
16 }
17
18 sc.close();
19 }
20}

Output

Enter a number: -3
-3.0 is Negative

What's going on

We compare the number with 0 to classify it as positive, negative, or zero.