Answer:
Following are the code to this question:
public class Main//defining a class-main
{
public static int sum(int[] nums)//defining a method sum that accepts array
{
int total = 0;//defining integer variable total
for(int num : nums) // use for-each loop
{
total += num;//add array value in total variable
}
return total;//use return keyword to return the total value
}
public static void main(String []ar )//defining a main method
{
int[] nums={1,2,3,4,5};//defining 1-D array nums
System.out.println(sum(nums));//use print function to call sum method
}
}
Output:
15
Explanation:
In the class "Main", a static method, "sum" is defined, that accepts array in its parameter and inside the method, an integer variable "total" is define, that uses the for each loop to add array value in a total variable and use a return keyword to return its value.
Inside the main method, an integer array nums are defined, that holds store some values and use the print function to call the sum method.