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:
- Method with return value – the method calculates the sum and returns it to the caller.
- 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
- Create a new Java class named
AddTwoNumbers. - Define a method with return value:
- Define a method without return value:
- Write the
mainmethod: - Call the method with return value:
- Call the method without return value:
- Run the program and observe the output.
Java Program to Add Two Numbers Using Methods
- Method with return value – returns the sum of two integers.
- Method without return value – directly prints the sum without returning it.
Input and Output
| Input | Method | Output |
|---|---|---|
| 15, 25 | AddWithReturn() | 40 |
| 15, 25 | AddWithoutReturn() | 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;
- Declares the package name
ebhor.methods.
public class AddTwoNumbers {
- Defines a public class named
AddTwoNumbers.
public int AddWithReturn(int num1, int num2) {
return num1 + num2;
}
- Defines a method with return value:
public void AddWithoutReturn(int num1, int num2) {
int sum = num1 + num2;
System.out.println("Sum = " + sum);
}
- Defines a method without return value:
public static void main(String[] args) {
- The main method:
AddTwoNumbers obj = new AddTwoNumbers();
- Creates an object of
AddTwoNumbersclass.
int a = 15, b = 25;
- Declares two integers
aandb.
int sum = obj.AddWithReturn(a, b);
System.out.println("Addition = " + sum);
- Calls
AddWithReturnmethod:
obj.AddWithoutReturn(a, b);
- Calls
AddWithoutReturnmethod:
}
- Closes the
mainmethod and the class.
Final Output
Addition = 40
Sum = 40