Sum of Positive Numbers in Array in Java

Program description:- Write a Java program to find the sum of positive numbers in an array. Display the sum value.

Array = {-10, 5, 0, -9, 18, 27, -36}
Sum of Positive numbers = 50

Array = {9, 8, 7, 0, -2, 5}
Sum of Positive numbers = 29

Array = {-50, -60, -70}
Sum of Positive numbers = 0

Prerequisite:- Array in Java, find length of array in Java, sum of array in Java

In this program, we will take input value for the array from the end-user, but you can take it explicitly. See:- how to take array input in Java. We will use a method to perform the operation. 

Procedure to find the sum of positive numbers in the given array in Java,
a) Take an array.
b) Declare a variable to store the sum of positive numbers. Assume the variable is “sum”. Initialize it with 0.
c) Traverse through the given array.
d) Check each element whether it is a positive number or not?
e) If it is a positive number then add it to the sum value.
f) Display the resultant value.

Java Program to Find the Sum of Positive Numbers in Array

import java.util.Scanner;
public class ArrayTest {
  public static void main(String[] args) {

    // create Scanner class object to take input
    Scanner scan = new Scanner(;

    // read size of the array
    System.out.print("Enter size of the array: ");
    int n = scan.nextInt();

    // create an int array of size N
    int numbers[] = new int[n];

    // take input for the array
    System.out.println("Enter array elements: ");
    for (int i = 0; i < n; ++i) {
      numbers[i] = scan.nextInt();

    // calculate the sum of positive numbers
    int sum = positiveSum(numbers);
    // display result
    System.out.println("Sum of positive numbers = " + sum);

    // close Scanner

  // method to display negative numbers
  public static int positiveSum(int[] numbers) {
    // variable
    int sum = 0;
    // traverse through the array
    for (int i : numbers) {
      if(i >= 0) sum += i;
    // return
    return sum;


Enter the size of the array: 7
Enter array elements:
-10 5 0 -9 18 27 -36
Sum of positive numbers = 50

Enter the size of the array: 6
Enter array elements:
9 8 7 0 -2 5
Sum of positive numbers = 29

Enter the size of the array: 3
Enter array elements:
-50 -60 -70
Sum of positive numbers = 0

Also See:- Find the Sum of Array in JavaAverage in Java using ArraySum of Two Arrays ElementsCompare Two Arrays in JavaMerge Two Arrays in JavaMerge Two Sorted ArraysCopy Array in Java

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *