How to Check If an Array Contains Only Positive Numbers in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if an array contains only positive numbers in Java. We will explore different approaches to achieve this, starting with a fundamental method using a loop to iterate through the array and check each element individually.

Following the basic loop method, we will delve into using the Java Stream API, a more modern and often more concise way to process collections. Finally, we will discuss how to handle zero and negative numbers within the context of determining if an array contains only positive values. This lab will provide you with practical skills in array manipulation and conditional logic in Java.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java(("Java")) -.-> java/ProgrammingTechniquesGroup(["Programming Techniques"]) java(("Java")) -.-> java/FileandIOManagementGroup(["File and I/O Management"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/BasicSyntaxGroup -.-> java/for_loop("For Loop") java/DataStructuresGroup -.-> java/arrays("Arrays") java/ProgrammingTechniquesGroup -.-> java/lambda("Lambda") java/FileandIOManagementGroup -.-> java/stream("Stream") subgraph Lab Skills java/if_else -.-> lab-559999{{"How to Check If an Array Contains Only Positive Numbers in Java"}} java/for_loop -.-> lab-559999{{"How to Check If an Array Contains Only Positive Numbers in Java"}} java/arrays -.-> lab-559999{{"How to Check If an Array Contains Only Positive Numbers in Java"}} java/lambda -.-> lab-559999{{"How to Check If an Array Contains Only Positive Numbers in Java"}} java/stream -.-> lab-559999{{"How to Check If an Array Contains Only Positive Numbers in Java"}} end

Loop Through Array for Positive Check

In this step, we will learn how to iterate through an array of numbers in Java and check if each number is positive. This is a fundamental operation in programming, allowing us to process collections of data.

First, let's create a new Java file named PositiveCheck.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing PositiveCheck.java.

Now, open the PositiveCheck.java file in the editor and add the following code:

public class PositiveCheck {

    public static void main(String[] args) {
        // Define an array of integers
        int[] numbers = {10, -5, 20, 0, 15, -8};

        // Loop through the array
        for (int i = 0; i < numbers.length; i++) {
            // Get the current number
            int currentNumber = numbers[i];

            // Check if the number is positive
            if (currentNumber > 0) {
                System.out.println(currentNumber + " is a positive number.");
            }
        }
    }
}

Let's break down this code:

  • public class PositiveCheck: This declares our class, matching the file name.
  • public static void main(String[] args): This is the main method where our program execution begins.
  • int[] numbers = {10, -5, 20, 0, 15, -8};: This line declares an array of integers named numbers and initializes it with some values. An array is a collection of elements of the same data type.
  • for (int i = 0; i < numbers.length; i++): This is a for loop. It's a control structure that allows us to repeat a block of code multiple times.
    • int i = 0: This initializes a counter variable i to 0.
    • i < numbers.length: This is the condition that is checked before each iteration. The loop continues as long as i is less than the length of the numbers array. numbers.length gives us the number of elements in the array.
    • i++: This increments the counter i by 1 after each iteration.
  • int currentNumber = numbers[i];: Inside the loop, this line accesses the element at the current index i from the numbers array and stores it in a variable called currentNumber. Array indices start from 0.
  • if (currentNumber > 0): This is an if statement. It checks if the currentNumber is greater than 0.
  • System.out.println(currentNumber + " is a positive number.");: This line is executed only if the if condition is true (i.e., the number is positive). It prints the positive number followed by the text " is a positive number.".

Save the PositiveCheck.java file (Ctrl+S or Cmd+S).

Now, let's compile and run this program in the Terminal. Make sure you are in the ~/project directory.

Compile the code:

javac PositiveCheck.java

If there are no errors, a PositiveCheck.class file will be created.

Now, run the compiled code:

java PositiveCheck

You should see the output showing only the positive numbers from the array.

10 is a positive number.
20 is a positive number.
15 is a positive number.

This demonstrates how to use a for loop to iterate through an array and apply a condition to each element. In the next step, we will explore a more modern way to achieve a similar result using Java's Stream API.

Use Stream API for Positive Numbers

In this step, we will explore a more modern and often more concise way to process collections in Java: the Stream API. Introduced in Java 8, Streams provide a powerful way to perform operations like filtering, mapping, and reducing on collections of data.

We will modify our previous example to use Streams to find the positive numbers in the array.

Open the PositiveCheck.java file in the editor again. Replace the existing code with the following:

import java.util.Arrays;

public class PositiveCheck {

    public static void main(String[] args) {
        // Define an array of integers
        int[] numbers = {10, -5, 20, 0, 15, -8};

        // Use Stream API to filter and print positive numbers
        Arrays.stream(numbers) // 1. Create a stream from the array
              .filter(number -> number > 0) // 2. Filter for positive numbers
              .forEach(number -> System.out.println(number + " is a positive number (Stream).")); // 3. Process each positive number
    }
}

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

  • import java.util.Arrays;: We need to import the Arrays class to use its stream() method.
  • Arrays.stream(numbers): This line converts our int array into an IntStream. A stream is not a data structure itself, but rather a sequence of elements that can be processed.
  • .filter(number -> number > 0): This is an intermediate operation on the stream. The filter() method takes a Predicate (a function that returns true or false) and keeps only the elements for which the predicate is true. Here, number -> number > 0 is a lambda expression, which is a concise way to write a function. It checks if each number in the stream is greater than 0.
  • .forEach(number -> System.out.println(number + " is a positive number (Stream)."));: This is a terminal operation. Terminal operations consume the stream and produce a result. The forEach() method performs an action for each element in the stream. Here, it prints each positive number along with a message.

Save the PositiveCheck.java file.

Now, compile and run the modified program in the Terminal:

javac PositiveCheck.java
java PositiveCheck

You should see the same output as before, but with the updated message:

10 is a positive number (Stream).
20 is a positive number (Stream).
15 is a positive number (Stream).

This demonstrates how the Stream API can be used to achieve the same result as the traditional for loop, often with more readable and expressive code, especially for more complex operations.

Handle Zero and Negative Numbers

In the previous steps, we focused on identifying positive numbers. Now, let's expand our program to also identify zero and negative numbers. This will give us a more complete picture of the numbers in our array.

We will modify the PositiveCheck.java file again to include checks for zero and negative numbers using the traditional for loop approach first, as it's often easier to understand conditional logic with if-else if-else statements.

Open the PositiveCheck.java file in the editor. Replace the existing code with the following:

public class PositiveCheck {

    public static void main(String[] args) {
        // Define an array of integers
        int[] numbers = {10, -5, 20, 0, 15, -8};

        // Loop through the array
        for (int i = 0; i < numbers.length; i++) {
            // Get the current number
            int currentNumber = numbers[i];

            // Check if the number is positive, negative, or zero
            if (currentNumber > 0) {
                System.out.println(currentNumber + " is a positive number.");
            } else if (currentNumber < 0) {
                System.out.println(currentNumber + " is a negative number.");
            } else {
                System.out.println(currentNumber + " is zero.");
            }
        }
    }
}

Here's what's new:

  • else if (currentNumber < 0): This is an else if statement. It checks if the currentNumber is less than 0, but only if the previous if condition (currentNumber > 0) was false.
  • else: This is an else statement. The code inside the else block is executed if none of the preceding if or else if conditions are true. In this case, if the number is not greater than 0 and not less than 0, it must be 0.

Save the PositiveCheck.java file.

Now, compile and run the modified program in the Terminal:

javac PositiveCheck.java
java PositiveCheck

You should now see output that categorizes each number in the array:

10 is a positive number.
-5 is a negative number.
20 is a positive number.
0 is zero.
15 is a positive number.
-8 is a negative number.

This demonstrates how to use if-else if-else statements to handle multiple conditions within a loop. This is a fundamental pattern for decision-making in programming.

You can also achieve similar results using the Stream API with more advanced techniques like partitioningBy or multiple filter operations, but the for loop with if-else if-else is a clear and straightforward approach for this specific task, especially for beginners.

Summary

In this lab, we learned how to check if an array contains only positive numbers in Java. We explored two primary methods: iterating through the array using a for loop and utilizing the Java Stream API.

We started by creating a Java class and using a for loop to examine each element in an integer array. We implemented a conditional check (if (currentNumber > 0)) to identify and print positive numbers. This fundamental approach demonstrated how to access and process individual elements within an array. While the provided content only detailed the loop method, the lab's structure indicates that subsequent steps would cover the Stream API and handling zero/negative numbers, providing a comprehensive understanding of different techniques for this common programming task.