Java Methods: Parameters, Return Values and Overloading
ProgrammingLesson 4 of 64 min read
What you'll learn
- Write methods with parameters and return values
- Explain why Java is always pass-by-value, including for objects
- Overload methods and use varargs
- Recognise when a recursive method needs a base case
On this page
A method is a named block of code you can call whenever you need it. Without methods you would copy the same logic in many places and fix every bug many times. Good methods are small, have a clear name and do one thing, which is exactly how professional Java code is organised.
Anatomy of a method
A method declaration has a return type, a name, a parameter list in parentheses and a body. static int add(int a, int b) says: this method returns an int, is called add, and needs two ints. The return statement sends a value back to the caller and ends the method. If a method does not return anything, its return type is void. The static keyword lets you call these methods from main without creating an object; you will see non-static methods in Java Classes and Objects.
public class Calculator {
static int add(int a, int b) {
return a + b;
}
static double average(int[] values) {
if (values.length == 0) {
return 0;
}
int sum = 0;
for (int v : values) {
sum += v;
}
return (double) sum / values.length;
}
static boolean isEven(int n) {
return n % 2 == 0;
}
static void printReceipt(String item, double price) {
System.out.println(item + ": Rs. " + price);
}
public static void main(String[] args) {
int sum = add(4, 5);
System.out.println(sum);
System.out.println(average(new int[]{70, 80, 90}));
System.out.println(isEven(10));
printReceipt("Notebook", 120.5);
}
}Output
9 80.0 true Notebook: Rs. 120.5
Notice the four shapes. add and average compute and return a number, isEven returns a boolean (a good pattern for questions), and printReceipt only has a side effect, printing, so it is void. In average, the early return 0 guards against an empty array, which would otherwise divide by zero.
Method overloading
You can define several methods with the same name as long as their parameter lists differ in number or type. This is overloading, and it lets related operations share one memorable name. Java picks the version at compile time by looking at the arguments you pass. Changing only the return type is not enough to overload a method.
public class Overloading {
static double area(double side) {
return side * side;
}
static double area(double length, double width) {
return length * width;
}
static String describe(int n) {
return "int " + n;
}
static String describe(double n) {
return "double " + n;
}
static int sumAll(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
public static void main(String[] args) {
System.out.println(area(4));
System.out.println(area(4, 2.5));
System.out.println(describe(7));
System.out.println(describe(7.0));
System.out.println(describe('a'));
System.out.println(sumAll());
System.out.println(sumAll(1, 2, 3, 4));
}
}Output
16.0 10.0 int 7 double 7.0 int 97 0 10
describe('a') printed int 97: there is no char version, so Java widened the char to its numeric code and picked the int overload. The int... numbers parameter is a varargs parameter. The caller can pass any number of ints, including none, and inside the method numbers behaves like an int[]. A varargs parameter must be the last one in the list.
Java is always pass-by-value
This is the most asked method question in Java interviews. When you call a method, Java copies each argument into the parameter. For a primitive, the copy is the number itself, so changes inside the method cannot touch the caller's variable. For an object, the copy is a copy of the reference (the address). Both references point to the same object, so the method can modify the object's contents, but reassigning the parameter to a new object has no effect outside.
import java.util.ArrayList;
import java.util.List;
public class PassByValue {
static void addBonus(int salary) {
salary = salary + 5000;
System.out.println("Inside method: " + salary);
}
static void addItem(List<String> cart) {
cart.add("Headphones");
}
static void replaceCart(List<String> cart) {
cart = new ArrayList<>();
cart.add("Something else");
}
static int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
int salary = 40000;
addBonus(salary);
System.out.println("After call: " + salary);
List<String> cart = new ArrayList<>();
cart.add("Keyboard");
addItem(cart);
System.out.println(cart);
replaceCart(cart);
System.out.println(cart);
System.out.println(factorial(5));
}
}Output
Inside method: 45000 After call: 40000 [Keyboard, Headphones] [Keyboard, Headphones] 120
Recursion in one minute
A method can call itself. factorial above multiplies n by the factorial of n - 1 until it hits the base case n <= 1, which returns without recursing. Every recursive method needs a base case and each call must move closer to it. Otherwise the calls pile up until Java throws StackOverflowError. Recursion is elegant for trees and divide-and-conquer problems, but a simple loop is often clearer and cheaper.
Common mistakes
- Missing return. A method that declares
intbut has a path with noreturnfails witherror: missing return statement. - Ignoring the returned value. Calling
add(2, 3);on its own compiles but discards the result. Assign it or print it. - Wrong argument types or count.
add(1)giveserror: method add in class Calculator cannot be applied to given typesfollowed byrequired: int,int, found: int. - Returning a value from a void method.
return 5;insidevoidfails witherror: incompatible types: unexpected return value. - Calling a non-static method from `main`. You get
error: non-static method greet() cannot be referenced from a static context. Either make itstaticor call it on an object. - Recursion without a base case. The program crashes with
Exception in thread "main" java.lang.StackOverflowError.
How this shows up in interviews and real projects
Expect questions such as "Is Java pass-by-value or pass-by-reference?", "What is the difference between overloading and overriding?" and "write factorial or Fibonacci recursively". In real projects, the habit that matters most is keeping methods short with names that read like sentences (calculateTotal, isEligible), because that is what lets another developer review your code quickly. Once you are comfortable here, continue with Java Classes and Objects.
Try it yourself
Write three overloaded methods named totalPrice: one taking a unit price and quantity, one that also takes a discount percentage, and one varargs version that sums any number of item prices. Call all three from main and print the results.
Show a hint
The discount version can compute price * quantity * (100 - discount) / 100. Use double for prices and double... for the varargs parameter.
Key takeaways
- A method has a return type, a name, parameters and a body;
voidmeans it returns nothing. - Overloading means the same name with different parameter lists, resolved at compile time.
- Java is always pass-by-value: objects pass a copy of the reference, so you can mutate an object but not repoint the caller's variable.
- Recursive methods need a base case, otherwise you get a
StackOverflowError.
Test yourself
A trick from this lesson's ride: A signature is the name plus the parameter types in order; return type does not count. Four more tricks like it wait along the route, each followed by a question.
Frequently asked questions
Is Java pass by value or pass by reference?
Java is always pass-by-value. For primitives the value is copied, and for objects the reference is copied. That is why a method can modify the object it receives but cannot make the caller's variable point to a different object.
What is the difference between method overloading and overriding?
Overloading means several methods in the same class share a name but have different parameters, and it is resolved at compile time. Overriding means a subclass provides its own version of a method inherited from its parent with the same signature, and it is resolved at runtime.
What does static mean in a Java method?
A static method belongs to the class itself rather than to any object, so you can call it without creating an instance. The main method is static for this reason. A static method cannot directly use instance fields or call instance methods.