# Java program to find sum of digits

0

Very basic coding practice and core Java written interview questions, sometimes faculty gives this question as homework to their students to check the basic understanding Java syntax and basic calculation logic similar to finding a factorial of a given number and printing Fibonacci series.
In this post, going to show very simple program to calculate the sum of given digits or say sum of given array elements.

```package com.javamakeuse.poc;

/**
*
* @author javamakeuse
*
*/
public class SumOfDigits {

// printing sum of digits from string
public static void printSumOfDigits(String digits) {
int sum = 0;
for (String digit : digits.split(",")) {
sum = sum + Integer.parseInt(digit);
}
System.out.println("Sum of digits (" + digits + ") is = " + sum);
}

// printing sum of array elements
public static void printSumOfArrayEle(int[] numArray) {
int sum = 0;
for (int num : numArray) {
sum = sum + num;
}
System.out.println("Sum of array element is = " + sum);
}

public static void main(String[] args) {
// calling method.
printSumOfDigits("1,2,3");
printSumOfArrayEle(new int[] { 1, 2, 3 });
}
}

```

OUTPUT:
Sum of digits (1,2,3) is = 6
Sum of array element is = 6