Methods, overloading and varargs
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Why methods
A method is a named block of code that you can call. Methods stop you from repeating yourself, they give pieces of logic a name, and they let you test and fix one thing at a time. When I read unfamiliar code, the method names tell me the story before I read a single line of the bodies.
Anatomy of a method
static double average(int[] values) {
// modifiers, return type, name, parameters
}
The return type says what the method gives back, and void means nothing. The parameters are the inputs. The return statement sends a value back and ends the method. In this lesson all methods are static, so we can call them from main without creating an object. In the classes lesson you will write methods that belong to objects.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(average(new int[]{80, 65, 92}));
System.out.println(isPrime(29) + " " + isPrime(30));
// Overloading
System.out.println(area(5)); // circle
System.out.println(area(4, 6)); // rectangle
System.out.println(area(3.0, 4.0, 5.0)); // triangle from three sides
// Varargs
System.out.println(sum());
System.out.println(sum(1, 2, 3, 4));
// Pass by value
int x = 10;
increment(x);
System.out.println("x is still " + x);
int[] data = {1, 2, 3};
doubleAll(data);
System.out.println(Arrays.toString(data));
reassign(data);
System.out.println(Arrays.toString(data));
System.out.println(factorial(10));
printBanner("Done", '*');
}
/**
* Calculates the average of the given values.
*
* @param values the numbers to average, must not be empty
* @return the average as a double
*/
static double average(int[] values) {
if (values.length == 0) {
throw new IllegalArgumentException("values must not be empty");
}
int total = 0;
for (int v : values) {
total += v;
}
return (double) total / values.length;
}
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) return false;
}
return true;
}
// Overloaded methods share a name but differ in parameters
static double area(double radius) {
return Math.PI * radius * radius;
}
static double area(double width, double height) {
return width * height;
}
static double area(double a, double b, double c) {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
static void increment(int value) {
value++; // changes only the local copy
}
static void doubleAll(int[] values) {
for (int i = 0; i < values.length; i++) {
values[i] *= 2; // changes the shared array
}
}
static void reassign(int[] values) {
values = new int[]{0, 0, 0}; // changes only the local reference
}
static long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
static void printBanner(String text, char symbol) {
String line = String.valueOf(symbol).repeat(text.length() + 4);
System.out.println(line);
System.out.println(symbol + " " + text + " " + symbol);
System.out.println(line);
}
}
Walking through it
average checks its input first and throws an exception for an empty array. Validating arguments at the top is called a guard clause. It keeps the rest of the method simple. The cast (double) total avoids integer division. The Javadoc comment above it, which starts with /**, documents the purpose, parameters and result. IDEs show this text when you hover over the method, so write one for any method that other people will call.
isPrime returns early. When the answer is known, return immediately. Deeply nested code is harder to follow than a few early returns.
Overloading means several methods with the same name but different parameter lists. The compiler picks the one that matches the call. The three area methods are called with one, two and three arguments. You cannot overload on the return type alone.
The varargs parameter int... numbers lets the caller pass any number of ints, including none. Inside the method, numbers is an ordinary array. A varargs parameter must be the last one in the list.
Pass by value
Java always passes arguments by value. For primitives, that means the method receives a copy. In increment, the change does not affect the caller's x. For objects and arrays, the value that is copied is the reference. Both the caller and the method point to the same array. So doubleAll changes the caller's data. But reassign only makes its own local variable point to a new array. The caller's reference is unchanged, and the output still shows the doubled values. People get this wrong in interviews and in real code, so run the program and compare the three outputs.
Recursion
A recursive method calls itself with a smaller problem until it reaches a base case. factorial is the standard example. Without the base case, you get a StackOverflowError.
What makes a good method
- It does one thing and its name says what, with a verb:
calculateTotal,isValid,printBanner. - It is short enough to read without scrolling.
Common mistakes
- Expecting a primitive argument to change inside the method.
- Ignoring the return value of a method that returns a result.
- Missing a return on some path. The compiler reports "missing return statement".
- Recursion without a base case.
- Methods that both calculate and print. Return the value and let the caller decide what to do with it.
Try it yourself
- Write
max(int... values)that returns the largest value and throws for no arguments. - Write overloaded
describemethods for anint, aStringand aboolean. - Write a recursive method that adds the digits of a number: 1234 gives 10.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(average(new int[]{80, 65, 92}));
System.out.println(isPrime(29) + " " + isPrime(30));
// Overloading
System.out.println(area(5)); // circle
System.out.println(area(4, 6)); // rectangle
System.out.println(area(3.0, 4.0, 5.0)); // triangle from three sides
// Varargs
System.out.println(sum());
System.out.println(sum(1, 2, 3, 4));
// Pass by value
int x = 10;
increment(x);
System.out.println("x is still " + x);
int[] data = {1, 2, 3};
doubleAll(data);
System.out.println(Arrays.toString(data));
reassign(data);
System.out.println(Arrays.toString(data));
System.out.println(factorial(10));
printBanner("Done", '*');
}
/**
* Calculates the average of the given values.
*
* @param values the numbers to average, must not be empty
* @return the average as a double
*/
static double average(int[] values) {
if (values.length == 0) {
throw new IllegalArgumentException("values must not be empty");
}
int total = 0;
for (int v : values) {
total += v;
}
return (double) total / values.length;
}
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) return false;
}
return true;
}
// Overloaded methods share a name but differ in parameters
static double area(double radius) {
return Math.PI * radius * radius;
}
static double area(double width, double height) {
return width * height;
}
static double area(double a, double b, double c) {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
static void increment(int value) {
value++; // changes only the local copy
}
static void doubleAll(int[] values) {
for (int i = 0; i < values.length; i++) {
values[i] *= 2; // changes the shared array
}
}
static void reassign(int[] values) {
values = new int[]{0, 0, 0}; // changes only the local reference
}
static long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
static void printBanner(String text, char symbol) {
String line = String.valueOf(symbol).repeat(text.length() + 4);
System.out.println(line);
System.out.println(symbol + " " + text + " " + symbol);
System.out.println(line);
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account