Java ProgramsControl FlowCheck Zero or Non-Zero

Check Zero or Non-Zero in Java

beginner·  Control Flow  ·  Conditional Statements

Problem

Zero is the unique integer that is neither positive nor negative — every other integer is non-zero.

Given an integer, determine whether it is zero or non-zero.

Input
0
Output
0 is zero

Java Program

Java
public class ZeroOrNonZero { public static void main(String[] args) { int n = 0; if (n == 0) { System.out.println(n + " is zero"); } else { System.out.println(n + " is non-zero"); } } }

Output

0 is zero

Core Logic

A single equality check against zero is all that's needed to separate the one special case from every other integer.

How It Works
  1. 1n == 0 tests the number directly against zero.
  2. 2Any value that fails this check, whether positive or negative, is reported as non-zero.
For n = 0, the equality check succeeds, so the number is reported as zero.
💡

Key Point: This check doesn't care about the sign of a non-zero number — negative and positive values both fall into the same 'non-zero' branch.

Key Concepts

if/elseequality operator

Related Programs