sum of arrays numbers in java code example
Example 1: sum of all numbers in array java
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
Example 2: sum numbers in array java
public class Exercise2 {
public static void main(String[] args) {
int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : my_array)
sum += i;
System.out.println("The sum is " + sum);
}
}
Example 3: sum of arrays numbers in java
public static void main(String[] args) {
String str = "a1b2c3d4";
char[] arr = str.toCharArray();
System.out.println(Arrays.toString(arr));
int sum = 0;
for(char each : arr ){
if( Character.isDigit(each) ){
sum += Integer.parseInt(""+each); }
}
System.out.println(sum);