Methods
Parameters, return types, overloading and how arguments are passed.
A method has a return type, a name and parameters. Use void when it returns nothing.
Java
public class Main {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.5, 3));
}
}Output
5 5.5
Two methods with one name but different parameter types is called overloading. Java picks the match at compile time.
Java passes by value
A method gets a copy of the value. For an object, that value is a reference, so the method can change the object itself but cannot make your variable point somewhere else.
Java
public class Main {
static void change(int n, int[] arr) {
n = 99;
arr[0] = 99;
}
public static void main(String[] args) {
int n = 1;
int[] arr = {1};
change(n, arr);
System.out.println(n + " " + arr[0]);
}
}Output
1 99