Detailed explanation of Java methods
-
What is the method?
A Java method is a collection of statements that together perform a function.
- Method is an ordered combination of steps to solve a class of problems
- Method is contained in a class or object
- Methods are created in the program and referenced elsewhere
Principle of design method: the original intention of method is function block, which is the collection of statement blocks to realize a certain function. When designing methods, we'd better keep the atomicity of methods, that is, a method only completes one function, which is conducive to our later expansion.
Example:
// addition public static int add(int a,int b) { return a + b; }
-
Method definition and call
-
Definition of method
Java methods are similar to functions in other languages. They are code fragments used to complete specific functions. Generally, defining a method includes the following syntax:
Method contains a method header and a method body. Here are all parts of a method:
-
Modifier: modifier, which is optional and tells the compiler how to call the method. Defines the access type of the method.
-
Return value type: the method may return a value. returnValueType is the data type of the return value of the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void.
-
Method name: is the actual name of the method. The method name and parameter table together constitute the method signature.
-
Parameter type: the parameter is like a placeholder. When called, the value is passed to the method. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.
- Formal parameter: used to receive external input data when the method is called.
- Argument: the data actually passed to the method when calling the method.
-
Method body: the method body contains specific statements that define the function of the method.
-
-
Method call
Calling method: object name Method name (argument list)
Java supports two methods of calling methods, which can be selected according to whether the method returns a value.
When a method returns a value, the method call is usually treated as a value. For example:
int larger = max(30,40);
If the return value of the method is void, the method call must be a statement.
System.out.println("Hello World!");
-
-
Method overloading
Overloading is a function with the same function name but different formal parameters in a class.
Rules for overloading methods:
- Method names must be the same.
- The parameter list must be different (different number, different type, different parameter arrangement order, etc.).
- The return types of methods can be the same or different.
- Just different return types are not enough to overload methods.
Realization theory:
If the method names are the same, the compiler will match one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error.
Example:
public static void main(String[] args) { int max = max(10, 20); System.out.println(max); double max1 = max(10.0, 20.0); System.out.println(max1); } public static double max(double i, double i1) { double result = -1; if (i == i1) { System.out.println("i == i1"); return result; } if (i > i1) { result = i; } else { result = i1; } return result; } public static int max(int i, int i1) { int result = -1; if (i == i1) { System.out.println("i == i1"); return result; } if (i > i1) { result = i; } else { result = i1; } return result; }
-
Command line parameters
Sometimes you want to pass a message to a program when it runs. This is achieved by passing command line parameters to the main() function.
Example:
public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println("args[" + i + "]: " + args[i]); } }
Execution steps:
-
Compile javac class names in command line mode java
-
Go back to src directory and enter java package name + class name space + parameter (String type)
-
-
Variable parameter
Starting with JDK 1.5, Java supports passing variable parameters of the same type to a method.
In the method declaration, add an ellipsis (...) after specifying the parameter type.
Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any ordinary parameter must be declared before it.
The essence of variable parameters is arrays
Example:
public static void main(String[] args) { printMax(1,2,3,4,5,6); printMax(new int[]{1,2,3}); } public static void printMax(int... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; } double result = numbers[0]; // Find maximum for (int i = 1; i < numbers.length; i++) { if (numbers[i] > result) { result = numbers[i]; } } System.out.println("The max value is:" + result); }
-
recursion
Recursion is: method A calls method A! Is to call yourself
Using recursion, we can solve some complex problems with simple programs. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem to solve. The recursive strategy only needs a small amount of program to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of code of the program. The ability of recursion is to define an infinite set of objects with limited statements.
The recursive structure consists of two parts:
- Recursive header: when not to call its own method. If there is no head, it will fall into a dead cycle
- Recursive body: when do I need to call my own method
// 5! 5*4*3*2*1 public static void main(String[] args) { System.out.println(f(5)); } public static int f(int n) { if (n == 1) { return 1; } return f(n - 1) * n; }
In the actual development situation, you can try not to use recursion without recursion. Because if the recursive chain is too long, the stack may overflow
-
Tail recursion
When the compiler detects that a function call is tail recursive, it overwrites the current activity record instead of creating a new one on the stack. The compiler can do this because the recursive call is the last statement to be executed in the current active period, so when the call returns, there is nothing else to do in the stack frame, so there is no need to save the stack frame. By overwriting the current stack frame instead of adding another one on it, the stack space used is greatly reduced, which makes the actual operation efficiency higher.
characteristic:
Tail recursion has two additional features on the basis of ordinary tail calls:
- What is called at the end is the function itself
- Through optimization, the calculation only takes up the constant stack space
Example:
// 5! 5*4*3*2*1 public static void main(String[] args) { System.out.println(f(5, 1)); } /** * Tail recursion * @param n * @param fn1 Store each calculated value * @return */ public static int f(int n, int fn1) { if (n == 1) { return fn1; // final result } return f(n - 1, fn1 * n); /* n fn1 First 5 Second 4 20 Third 3 60 Fourth time 2 120 The fifth time 1 returns fn1 */ }