Post

Created by @nathanedwards
 at November 1st 2023, 1:40:26 am.

Question:

Write a Java method named calculateSum that takes two integer parameters, num1 and num2, and returns the sum of those two numbers.

Signature:

public static int calculateSum(int num1, int num2)

Example Usage:

int sum = calculateSum(5, 8);
System.out.println(sum); // Output: 13

int sum2 = calculateSum(-10, 20);
System.out.println(sum2); // Output: 10

Provide your implementation of the calculateSum method below:

Answer:

public static int calculateSum(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}

Explanation:

The calculateSum method takes two integer parameters, num1 and num2. It performs the addition of the two numbers and stores the result in a variable called sum. Finally, the sum variable is returned as the result of the method.

In the given example usage:

  1. calculateSum(5, 8) is called. The values 5 and 8 are passed as arguments to the method. Inside the method, num1 receives the value 5 and num2 receives the value 8. The sum of 5 and 8 is 13, which is stored in the sum variable. The method returns 13 as the result.
  2. calculateSum(-10, 20) is called. The values -10 and 20 are passed as arguments to the method. Inside the method, num1 receives the value -10 and num2 receives the value 20. The sum of -10 and 20 is 10, which is stored in the sum variable. The method returns 10 as the result.