How to Check If a Number Is Positive in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a number is positive in Java. We will start by writing a simple program to compare a number with zero using basic conditional statements.

You will then extend this knowledge to test with both integer and double data types, understanding how to handle different numerical representations. Finally, we will explore how to handle edge cases, specifically focusing on how to correctly identify and manage the case where the number is zero.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java/BasicSyntaxGroup -.-> java/data_types("Data Types") java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/variables("Variables") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/BasicSyntaxGroup -.-> java/output("Output") subgraph Lab Skills java/data_types -.-> lab-559968{{"How to Check If a Number Is Positive in Java"}} java/operators -.-> lab-559968{{"How to Check If a Number Is Positive in Java"}} java/variables -.-> lab-559968{{"How to Check If a Number Is Positive in Java"}} java/if_else -.-> lab-559968{{"How to Check If a Number Is Positive in Java"}} java/output -.-> lab-559968{{"How to Check If a Number Is Positive in Java"}} end

Compare Number with Zero

In this step, we will write a simple Java program to compare a number with zero. This will introduce you to basic conditional statements in Java, specifically the if statement. Conditional statements allow your program to make decisions based on certain conditions.

  1. First, make sure you are in the correct directory. Open the Terminal at the bottom of the WebIDE and type the following command, then press Enter:

    cd ~/project

    This ensures you are in the ~/project directory where we will create our Java file.

  2. Now, let's create a new Java file named CompareNumber.java. You can do this by right-clicking in the File Explorer on the left, selecting "New File", and typing CompareNumber.java. Alternatively, you can use the Terminal:

    touch CompareNumber.java
  3. Open the CompareNumber.java file in the Code Editor by clicking on it in the File Explorer.

  4. Copy and paste the following Java code into the editor:

    public class CompareNumber {
        public static void main(String[] args) {
            int number = 10; // We will compare this number with zero
    
            if (number > 0) {
                System.out.println("The number is positive.");
            }
        }
    }

    Let's look at the new parts of this code:

    • int number = 10;: This line declares a variable named number of type int (integer) and assigns it the value 10. Variables are used to store data in your program.
    • if (number > 0): This is an if statement. It checks if the condition inside the parentheses (number > 0) is true. If the condition is true, the code inside the curly braces {} that follows will be executed.
    • System.out.println("The number is positive.");: This line will only be executed if the number is greater than 0.
  5. Save the file (Ctrl+S or Cmd+S).

  6. Now, compile the Java program using the javac command in the Terminal:

    javac CompareNumber.java

    If there are no errors, a CompareNumber.class file will be created in the ~/project directory.

  7. Finally, run the compiled program using the java command:

    java CompareNumber

    Since the number variable is set to 10 (which is greater than 0), you should see the following output:

    The number is positive.

You have successfully written and run a Java program that uses an if statement to compare a number with zero. In the next step, we will expand this program to handle different cases.

Test with Integer and Double

In the previous step, we compared an integer with zero. Java supports different types of numbers, including integers (whole numbers) and floating-point numbers (numbers with decimal points). In this step, we will modify our program to test with both integer and double data types and introduce the else statement to handle the case where the number is not positive.

  1. Open the CompareNumber.java file in the WebIDE editor if it's not already open.

  2. Modify the code to include an else block. Replace the existing code with the following:

    public class CompareNumber {
        public static void main(String[] args) {
            int number = -5; // Let's test with a negative integer
    
            if (number > 0) {
                System.out.println("The number is positive.");
            } else {
                System.out.println("The number is not positive.");
            }
        }
    }

    Here's what's new:

    • int number = -5;: We changed the value of number to -5 to test the else condition.
    • else { ... }: The else block is executed if the condition in the preceding if statement is false. In this case, if number > 0 is false, the code inside the else block will run.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac CompareNumber.java
  5. Run the compiled program:

    java CompareNumber

    Since number is -5, the if condition (-5 > 0) is false, so the else block will be executed. You should see the output:

    The number is not positive.
  6. Now, let's test with a double (a floating-point number). Modify the code again:

    public class CompareNumber {
        public static void main(String[] args) {
            double decimalNumber = 3.14; // Test with a positive double
    
            if (decimalNumber > 0) {
                System.out.println("The number is positive.");
            } else {
                System.out.println("The number is not positive.");
            }
        }
    }

    We changed the variable type to double and assigned it a decimal value.

  7. Save the file.

  8. Compile the program:

    javac CompareNumber.java
  9. Run the program:

    java CompareNumber

    Since decimalNumber is 3.14 (which is greater than 0), the if condition will be true, and you should see the output:

    The number is positive.

You've now seen how to use the else statement and how the comparison works with both integer and double data types. In the next step, we will handle the specific case where the number is exactly zero.

Handle Edge Cases Like Zero

In the previous steps, we handled positive and non-positive numbers. However, we haven't specifically addressed the case where the number is exactly zero. In programming, handling these "edge cases" is important to ensure your program behaves correctly in all situations. In this step, we will use the else if statement to add a specific check for zero.

  1. Open the CompareNumber.java file in the WebIDE editor.

  2. Modify the code to include an else if block to check for zero. Replace the existing code with the following:

    public class CompareNumber {
        public static void main(String[] args) {
            int number = 0; // Let's test with zero
    
            if (number > 0) {
                System.out.println("The number is positive.");
            } else if (number == 0) {
                System.out.println("The number is zero.");
            } else {
                System.out.println("The number is negative.");
            }
        }
    }

    Let's look at the changes:

    • int number = 0;: We set the number to 0 to test the new condition.
    • else if (number == 0): This is an else if statement. It's checked only if the preceding if condition (number > 0) is false. The condition number == 0 checks if the value of number is exactly equal to 0. Note the double equals sign (==) for comparison, as a single equals sign (=) is used for assignment.
    • System.out.println("The number is zero.");: This line will be executed if the number is exactly 0.
    • The final else block now specifically handles the case where the number is neither positive nor zero, meaning it must be negative.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac CompareNumber.java
  5. Run the compiled program:

    java CompareNumber

    Since number is 0, the first if condition (0 > 0) is false. The else if condition (0 == 0) is true, so its block will be executed. You should see the output:

    The number is zero.
  6. Now, let's test with a negative number again. Change the value of number to -10:

    public class CompareNumber {
        public static void main(String[] args) {
            int number = -10; // Test with a negative number
    
            if (number > 0) {
                System.out.println("The number is positive.");
            } else if (number == 0) {
                System.out.println("The number is zero.");
            } else {
                System.out.println("The number is negative.");
            }
        }
    }
  7. Save the file.

  8. Compile the program:

    javac CompareNumber.java
  9. Run the program:

    java CompareNumber

    Since number is -10, the if condition (-10 > 0) is false, and the else if condition (-10 == 0) is also false. Therefore, the final else block will be executed, and you should see the output:

    The number is negative.

You have now successfully used if, else if, and else statements to compare a number with zero and determine if it is positive, negative, or zero. This is a fundamental pattern for making decisions in your Java programs.

Summary

In this lab, we began by learning how to set up our development environment by navigating to the correct directory and creating a new Java file. We then introduced the fundamental concept of conditional statements in Java using the if statement. By writing a simple program, we learned how to declare an integer variable, assign it a value, and use the > operator within an if condition to check if the number is greater than zero. We saw how the code block within the if statement is executed only when the condition is true, demonstrating how to print a message indicating that the number is positive.