BeginnerLesson 5 of 16
Methods – Java
Reusable building blocks: parameters, return values, overloading, varargs.
In Java every method belongs to a class. static means: the method belongs to the class itself, you do not need an object. void means: no return value.
public class Main {
static int quadrat(int x) {
return x * x;
}
static void gruss(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
gruss("Ada");
System.out.println(quadrat(7)); // 49
}
}Java has no default values for parameters. Instead you overload methods (same name, different parameters) and use varargs (...) for any number of arguments.
static String begruesse(String name, String gruss) {
return gruss + ", " + name + "!";
}
static String begruesse(String name) {
return begruesse(name, "Hello");
}
static int summe(int... zahlen) {
int s = 0;
for (int z : zahlen) s += z;
return s;
}
System.out.println(begruesse("Ada")); // Hello, Ada!
System.out.println(begruesse("Linus", "Hi")); // Hi, Linus!
System.out.println(summe(1, 2, 3, 4)); // 10Java always uses call by value: primitives are copied, and for objects the reference is copied. So the method can modify the object, but cannot redirect the caller's variable.
static void aendere(int x, StringBuilder sb) {
x = 99; // changes only the local copy
sb.append("!"); // modifies the shared object
}
int a = 1;
var sb = new StringBuilder("Hi");
aendere(a, sb);
System.out.println(a + " " + sb); // 1 Hi!TipKeep methods short and give them meaningful names in camelCase (
berechneSumme). A method should do exactly one job.