Java Program to Add Two Numbers Using Methods (With and Without Return Value)

When learning Java, understanding how to use methods is an important step toward writing clean and reusable code. Methods help us divide a program into smaller parts and avoid repeating logic.

In this tutorial, we will write a Java program to add two numbers using methods. We will cover two different approaches:

  1. Method with return value – the method calculates the sum and returns it to the caller.
  2. Method without return value – the method calculates the sum and directly prints it without returning.

By the end of this tutorial, you will clearly understand the difference between methods that return values and those that don’t.


Steps to Create the Program

  1. Create a new Java class named AddTwoNumbers.
  2. Define a method with return value:
  3. Define a method without return value:
  4. Write the main method:
  5. Call the method with return value:
  6. Call the method without return value:
  7. Run the program and observe the output.

Java Program to Add Two Numbers Using Methods

  1. Method with return value – returns the sum of two integers.
  2. Method without return value – directly prints the sum without returning it.

Input and Output

InputMethodOutput
15, 25AddWithReturn()40
15, 25AddWithoutReturn()Sum = 40
package ebhor.methods;

public class AddTwoNumbers {

    // Method with return value
    public int AddWithReturn(int num1, int num2) {
        return num1 + num2;
    }

    // Method without return value
    public void AddWithoutReturn(int num1, int num2) {
        int sum = num1 + num2;
        System.out.println("Sum = " + sum);
    }

    public static void main(String[] args) {
        AddTwoNumbers obj = new AddTwoNumbers();

        int a = 15, b = 25;

        // Using method with return value
        int sum = obj.AddWithReturn(a, b);
        System.out.println("Addition = " + sum);

        // Using method without return value
        obj.AddWithoutReturn(a, b);
    }
}

Output

Addition = 40
Sum = 40

Java Program Explanation (Line by Line)

package ebhor.methods;
  1. Declares the package nameebhor.methods.
public class AddTwoNumbers {
  1. Defines a public class named AddTwoNumbers.
public int AddWithReturn(int num1, int num2) {
    return num1 + num2;
}
  1. Defines a method with return value:
public void AddWithoutReturn(int num1, int num2) {
    int sum = num1 + num2;
    System.out.println("Sum = " + sum);
}
  1. Defines a method without return value:
public static void main(String[] args) {
  1. The main method:
AddTwoNumbers obj = new AddTwoNumbers();
  1. Creates an object of AddTwoNumbers class.
int a = 15, b = 25;
  1. Declares two integers a and b.
int sum = obj.AddWithReturn(a, b);
System.out.println("Addition = " + sum);
  1. Calls AddWithReturn method:
obj.AddWithoutReturn(a, b);
  1. Calls AddWithoutReturn method:
}
  1. Closes the main method and the class.

Final Output

Addition = 40
Sum = 40