Java Functions: Usage & Examples
In Java, functions are reusable blocks of code used to perform specific tasks. They can take zero or more parameters and can return a value. In Java, the usage of functions is as follows:
- Declare a function by using keywords such as “public,” “private,” or “protected” to specify the return type and function name. For example:
public int add(int num1, int num2) {
return num1 + num2;
}
- Invoke a function: Calling a function by using the function name and a list of arguments. For example:
int result = add(5, 3);
- Function parameters: Functions can accept zero or more parameters, and the types and names of the parameters need to be specified in the function declaration. For example:
public void printMessage(String message) {
System.out.println(message);
}
- Return value: A function can return a value, the type of the return value is specified in the function declaration. Use the keyword “return” to return the value. For example:
public int multiply(int num1, int num2) {
return num1 * num2;
}
- Function overloading: Java allows function overloading, which means multiple functions with the same name can exist in the same class as long as they have different parameter types, numbers, or order. For example:
public int add(int num1, int num2) {
return num1 + num2;
}
public double add(double num1, double num2) {
return num1 + num2;
}
- Anonymous functions: Java supports creating anonymous functions using lambda expressions or functional interfaces. For example:
Function<Integer, Integer> square = (x) -> x * x;
int result = square.apply(5); // 结果为25
In Java, functions are used to perform specific tasks, they can take parameters and return a value. Functions can be declared, called, have parameters and return values, as well as be overloaded and use anonymous functions.