Java ProgramsControl FlowCheck Positive or Negative

Check Positive or Negative in Java

beginner·  Control Flow  ·  Conditional Statements

Problem

Every integer is exactly one of three things: positive, negative, or zero, decided by comparing it against zero.

Given an integer, determine whether it is positive, negative, or zero.

Input
-7
Output
-7 is negative

Java Program

Java
public class PositiveOrNegative { public static void main(String[] args) { int n = -7; if (n > 0) { System.out.println(n + " is positive"); } else if (n < 0) { System.out.println(n + " is negative"); } else { System.out.println(n + " is zero"); // neither check matched, so n must be exactly zero } } }

Output

-7 is negative

Core Logic

Testing the number against zero, first for greater-than and then for less-than, separates all three outcomes in order.

How It Works
  1. 1n > 0 is checked first — if it holds, the number is positive.
  2. 2n < 0 is checked next — if the first check failed but this one holds, the number is negative.
  3. 3If neither check holds, n must be exactly zero, and the final else branch reports that.
For n = -7, the first check fails since -7 isn't greater than 0, but the second check succeeds, so it's reported as negative.
💡

Key Point: Checking greater-than and less-than separately, rather than a single equality test, is what lets zero fall out as its own distinct case in the final else branch.

Key Concepts

if / else if / elsecomparison operator

Approach 2: Using Integer.signum()

Java
public class PositiveOrNegativeSignum { public static void main(String[] args) { int n = -7; // signum() normalizes any int down to exactly -1, 0, or 1 int sign = Integer.signum(n); if (sign == 1) { System.out.println(n + " is positive"); } else if (sign == -1) { System.out.println(n + " is negative"); } else { System.out.println(n + " is zero"); // signum() only ever returns 1, -1, or 0 } } }

Output

-7 is negative

Core Logic

Java's Integer.signum() already reduces any integer down to exactly -1, 0, or 1, so branching on the sign becomes branching on one of three fixed values.

How It Works
  1. 1Integer.signum(n) normalizes n to 1 if it's positive, -1 if it's negative, or 0 if it's exactly zero.
  2. 2The same three-way if/else structure then branches on that normalized sign value instead of on n directly.
Integer.signum(-7) returns -1, so the sign == -1 branch fires and reports the number as negative.
💡

Key Point: Integer.signum() is most useful when the sign itself needs to be compared, stored, or passed around as a value — like sorting by sign — rather than for a single one-off check.

Key Concepts

Integer.signum()built-in method

Related Programs