In Java, a function is a method. That is, the way to implement a function.
Format of the function
Modifier returns a value type function name (parameter type parameter) {
logical processing;
return processing results; The return keyword is used to end the function and returns the processing result to the caller. The void type can omit return, but when compiled into a. class file, there is a return in the code.
}
How do you define a function?
When defining a function, make two points clear:
1. What is the result of this feature?
2. What are the parameters that this function needs to pass?
Common misunderstanding of new handwriting function
Error code example
Class MethodDemo2
{
public static void Main (String [] args) {
Add (4,5);
}
public static void Add (int a, int b) {
System.out.println (A + B);
Return
}
}
The above code, although the result is correct, is not logical. Because the Add (int a, int b) function is only used for addition operations, there should be no printing operations.
The right approach should be a function that corresponds to a function.
Class MethodDemo2 {
public static void Main (String [] args) {
int sum = Add (4,5);
SYSTEM.OUT.PRINTLN (sum); The printing function should be a standalone method
}
public static int Add (int a, int b) {//The arithmetic function is only responsible for the operation
return a + B;
}
}
Suggestions
A function should not exceed 20 lines, if the logic is more, you can split multiple functions, called by the function name. The purpose is to facilitate debugging.
Overloading of functions
A function with the same name in a class is called a function overload (overload), as long as the number of arguments is different from the parameter type. Is independent of the return value type.
Notes for Java functions