Java · Lesson 9 of 15
Methods and Overloading
Parameters, return values, overloading, varargs and pass-by-value.
- Beginner
- 12 min read
- 3 objectives
Before this lessonLesson 8: Arrays
What you will learn
- Write methods with return types
- Overload a method
- Explain pass-by-value
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
A method is a named block of code you can call again and again. It declares what it takes in (parameters) and what it gives back (return type), or void if nothing.
Parameters and return values
public class Main {
static int square(int n) {
return n * n;
}
static void greet(String name) {
System.out.println("Hi " + name);
}
public static void main(String[] args) {
greet("Ada");
System.out.println(square(7));
}
}Hi Ada 49
Overloading
Several methods can share a name if their parameter lists differ. The compiler picks the one that matches the call.
public class Main {
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; }
static int add(int a, int b, int c) { return a + b + c; }
public static void main(String[] args) {
System.out.println(add(1, 2));
System.out.println(add(1.5, 2.5));
System.out.println(add(1, 2, 3));
}
}3 4.0 6
Varargs
public class Main {
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(1, 2, 3, 4));
}
}0 10
Java is always pass-by-value
A method receives a copy of each argument. For primitives that copy is the number itself, so changing it does nothing to the caller. For objects the copy is the reference: the method can change the object's contents, but reassigning the parameter does not affect the caller's variable.
public class Main {
static void change(int n, StringBuilder sb) {
n = 99;
sb.append("!");
sb = new StringBuilder("other");
}
public static void main(String[] args) {
int n = 1;
StringBuilder sb = new StringBuilder("hey");
change(n, sb);
System.out.println(n + " " + sb);
}
}1 hey!
