How to Check If a Number Is Negative in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a number is negative in Java. We will start by writing a simple program using conditional statements to determine if a number is less than zero.

You will then explore how to apply this check to different numeric data types and learn how to include zero in your negative number check, providing a comprehensive understanding of handling negative values in Java.


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-559966{{"How to Check If a Number Is Negative in Java"}} java/operators -.-> lab-559966{{"How to Check If a Number Is Negative in Java"}} java/variables -.-> lab-559966{{"How to Check If a Number Is Negative in Java"}} java/if_else -.-> lab-559966{{"How to Check If a Number Is Negative in Java"}} java/output -.-> lab-559966{{"How to Check If a Number Is Negative in Java"}} end

Check if Number Is Less Than Zero

In this step, we will write a simple Java program to check if a given number is less than zero. This will introduce you to basic conditional statements in Java.

  1. First, make sure you are in the ~/project directory. You can use the command cd ~/project in the Terminal if needed.

  2. Create a new Java file named NumberCheck.java in the ~/project directory. You can do this by right-clicking in the File Explorer on the left, selecting "New File", and typing NumberCheck.java.

  3. Open the NumberCheck.java file in the Code Editor and paste the following code:

    public class NumberCheck {
        public static void main(String[] args) {
            int number = -5; // Our number to check
    
            if (number < 0) {
                System.out.println("The number is less than zero.");
            }
        }
    }

    Let's look at the new parts:

    • int number = -5;: This line declares a variable named number of type int (integer) and assigns it the value -5. Variables are like containers that hold data.
    • 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 {} is executed.
    • System.out.println("The number is less than zero.");: This line will only be executed if the number is indeed less than 0.
  4. Save the file (Ctrl+S or Cmd+S).

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

    javac NumberCheck.java

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

  6. Run the compiled program using the java command:

    java NumberCheck

    You should see the output:

    The number is less than zero.

    This confirms that our if statement correctly identified that the number -5 is less than zero.

Test with Different Numeric Types

In this step, we will explore how our program behaves with different types of numbers, specifically positive numbers and zero. This will help you understand how the if statement works when the condition is false.

  1. Open the NumberCheck.java file in the Code Editor.

  2. Modify the value of the number variable to a positive number, for example, 10. The code should now look like this:

    public class NumberCheck {
        public static void main(String[] args) {
            int number = 10; // Our number to check
    
            if (number < 0) {
                System.out.println("The number is less than zero.");
            }
        }
    }
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac NumberCheck.java

    Again, if compilation is successful, you won't see any output.

  5. Run the compiled program:

    java NumberCheck

    This time, you should see no output. This is because the condition number < 0 (which is 10 < 0) is false, so the code inside the if block is skipped.

  6. Now, let's test with zero. Modify the value of the number variable to 0:

    public class NumberCheck {
        public static void main(String[] args) {
            int number = 0; // Our number to check
    
            if (number < 0) {
                System.out.println("The number is less than zero.");
            }
        }
    }
  7. Save the file.

  8. Compile the program:

    javac NumberCheck.java
  9. Run the program:

    java NumberCheck

    Again, you should see no output. This is because 0 < 0 is also false.

This step demonstrates that the code inside the if statement only runs when the condition is strictly true. In the next step, we will modify the condition to include zero in our check for non-positive numbers.

Include Zero in Negative Check

In the previous step, we saw that our program only prints the message if the number is strictly less than zero. Often, we might want to include zero when checking for non-positive numbers (numbers that are less than or equal to zero). In this step, we will modify our condition to achieve this.

  1. Open the NumberCheck.java file in the Code Editor.

  2. Modify the condition in the if statement from number < 0 to number <= 0. The <= operator means "less than or equal to".

    The updated code should look like this:

    public class NumberCheck {
        public static void main(String[] args) {
            int number = 0; // Our number to check
    
            if (number <= 0) { // Changed condition
                System.out.println("The number is less than or equal to zero."); // Updated message
            }
        }
    }

    We also updated the message inside the println statement to be more accurate.

  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac NumberCheck.java
  5. Run the compiled program:

    java NumberCheck

    This time, since number is 0 and the condition 0 <= 0 is true, you should see the output:

    The number is less than or equal to zero.
  6. Let's quickly test with a negative number again. Change the value of number back to -5:

    public class NumberCheck {
        public static void main(String[] args) {
            int number = -5; // Our number to check
    
            if (number <= 0) { // Changed condition
                System.out.println("The number is less than or equal to zero."); // Updated message
            }
        }
    }
  7. Save the file.

  8. Compile the program:

    javac NumberCheck.java
  9. Run the program:

    java NumberCheck

    You should see the output:

    The number is less than or equal to zero.

    This confirms that our updated condition works for both negative numbers and zero.

You have now successfully used the "less than or equal to" operator (<=) to include zero in your conditional check. This is a common requirement in programming when dealing with ranges of numbers.

Summary

In this lab, we learned how to check if a number is negative in Java. We started by writing a basic Java program using an if statement to determine if an integer is less than zero. This involved creating a Java file, writing the code with a variable and a conditional check, compiling the program using javac, and running it with java to observe the output. This initial step introduced the fundamental concept of using conditional logic (if statements) to evaluate numerical conditions in Java.