Same name, different parameters
You can have several methods with the same name as long as their parameters are different. Java picks the right one by looking at what you pass in. This is called overloading:
public class Main {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
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, 3, 4));
System.out.println(add(1.5, 2.25));
}
}Output
5 9 3.75
You already use overloading: println has versions for ints, doubles, Strings and more.
Scope: where a variable lives
A variable only exists inside the { } block where it was created. That area is its scope:
public class Main {
static void test() {
int secret = 42;
System.out.println(secret);
}
public static void main(String[] args) {
test();
System.out.println(secret);
}
}Output (the program does not compile)
Main.java:9: error: cannot find symbol
System.out.println(secret);
^
symbol: variable secret
location: class Mainsecret belongs to test, so main can't see it.
Java passes copies
When you pass a number to a method, the method gets a copy. Changing the copy doesn't change the original:
public class Main {
static void addTen(int x) {
x = x + 10;
System.out.println("Inside: " + x);
}
public static void main(String[] args) {
int value = 5;
addTen(value);
System.out.println("Outside: " + value);
}
}Output
Inside: 15 Outside: 5
Tip: If you want the new value,
returnit:value = addTen(value);