This entry is about using the sum() method in Java. This method is used when the user wants to add two integers to return the sum of those arguments. Those arguments can include the following data types: int, float, double, and long. I’ll show you three different ways to find a sum.
Problem 1: Find the sum of two arguments.
public class JavaJourals{
public static void sum(int a, int b){
System.out.println("The sum of problem 1 is: " + Integer.sum(a,b));
}
public static void main(String []args){
int a = 12;
int b = 3;
sum(a,b);
}
}
Output
The sum of problem 1 is: 15
Problem 2: Find the sum of multiple arguments.
public class JavaJourals{
public static void multiSum(int a, int b, int c){
int sum = a+b+c;
System.out.println("The sum of problem 2 is: " + sum);
}
public static void main(String []args){
int a = 12;
int b = 3;
int c = 27;
multiSum(a,b,c);
}
}
Output
The sum of problem 2 is: 42
Problem 3: Find the sum using a loop.
public class JavaJourals{
public static void loop(int[] arr, int sum){
for(int i = 0; i < arr.length; i++){
sum += arr[i];
}
System.out.println("The sum of problem 3 is: " + sum);
}
public static void main(String []args){
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
loop(arr, sum);
}
}
Output
The sum of problem 3 is: 15
Feel free to comment, share, and check out some of the resources below. Thanks for reading!