Solving the ‘Return the Sum of Two Numbers’ Java Programming Problem

A Beginner’s Guide to Writing a Method That Adds Two Integers and Returns Their Sum

Max N
2 min readJun 12, 2023
Photo by Roman Mager on Unsplash

Introduction

In this article, we’ll walk through a step-by-step guide on how to write a method that takes two integers as arguments and returns their sum.

Step 1: Define the Method

To start, we need to define the method. In Java, a method is a block of code that performs a specific task. We’ll name our method SumOfTwoNumbers and specify that it takes two integer arguments:

public static int SumOfTwoNumbers(int num1, int num2) {
// code goes here
}

Step 2: Add the Integers

Next, we need to add the two integers together. We can do this using the + operator:

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

Step 3: Return the Sum

Finally, we need to return the sum. In Java, we use the return keyword to return a value from a method:

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

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.