Chapter V function

Posted by phpORcaffine on Fri, 24 Dec 2021 01:40:10 +0100

The function mainly solves those repetitive and independent code blocks, extracts these code blocks, generates functions, facilitates later calls, and solves the problem of code redundancy.

Syntax format of functions in Java:

Permission modifier function type modifier return value type function name(parameter list){
    Function body
    return Return value;
}

Permission modifier: indicates the calling permission of the function. public protected does not write private by default

Function type modifier: static function; Native native function; Abstract abstract function; synchronized synchronization function

Return value type: it is the result of function calculation. If it needs to be returned to the caller, it will be marked as the data type of calculation result (downward compatibility); if it does not need to be returned, it will be written as void

Function name: name the description of the function

Parameter list: it refers to some data transferred from the outside to the function. These data are generally called formal parameters, and the data transferred from the outside is called actual parameters

Function body: it is the code block with independent functions

Return: only indicates the end of the function! If there is a return value, write it after return; If there is no return value and the return value is not written after return, return is hidden and not written!

Return value: the result of function calculation

Functions can be divided into:

① Return with parameters ② return without parameters ③ return without parameters ④ return without parameters

How to design a function?

Consider the function of the function

Consider whether the function accepts data

Consider whether there are calculation results

Consider whether the result is returned

5.1 function memory operation principle

The operation of functions is based on the stack. Each function is an element in the stack, We call this element stack frame (stack frame mainly contains all bytecode information of the function. In extreme cases, if a stack frame is too large, the stack structure will not be saved, resulting in stack memory overflow exception StackOverFlowError; if too many stack frames are entered, the stack memory will not be saved, and the stack memory will overflow). Generally, the first stack frame into the stack is the main function. Once a stack frame is entered into the stack In the stack, it starts to execute line by line. If other functions are called during execution, the current stack frame stops running, the stack frame of the new function enters the stack and starts to run line by line until the run is completed. If return is encountered, the stack pops up and the stack frame at the top of the current stack continues to execute.

Variables created in a function are collectively referred to as local variables (the access scope of the variable is only in the function), so formal parameters are also local variables.

public static void main(String args[]) {
    int a = 1;
    int b = 2;
    int c = 3;
    int d = add(a,b,c);
    System.out.println(d);
}
public static int add(int a, int b, int c) {
    return a + b + c;
}

 

5.2 function overloading

Overloading means that there are multiple functions with the same name in a class.

public static void main(String[] args) {
    int a = 3;
    int b = 7;
    int c = add(a,b);
}
public static int add(int a,int b) {
    return a + b;
}

When the function parameter is int and the return value is int, the function can run normally.

public static void main(String[] args) {
    int a = 3;
    int b = 7;
    int c = add(a,b);
    double d = add(3.14,3.56);
}
public static int add(int a,int b) {
    return a + b;
}

When the function parameter is of type int and the return value is of type int, but the actual added number type is double, the function will report an error.

public static void main(String[] args) {
    add(1,2,3);
    add(1,2);
    add(3.14,3);
    add(3,3.14);
    add(0.9,0.8);
}
public static int add(int a,int b,int c) { //add(int,int,int)
    System.out.println("int int int");
    return a + b + c;
}
public static int add(int a,int b) { //add(int,int)
    System.out.println("int int");
    return a + b;
}
//The return value type of a function does not necessarily depend on the parameter type, but on the function function calculation logic
//It highlights that function overloading is also independent of the return value type of the function!
public static String add(double a,int b) { //add(double,int)
    System.out.println("double int");
    return "" + a + b;
}
public static char add(int a, double b) { //add(int,double)
    System.out.println("int double");
    return (char)(a + b);
}
public static float add(double a,double b) { //add(double,double)
    System.out.println("double double");
    return (float)(a + b);
}

1 when calling these functions with duplicate names, first consider the number of corresponding parameters

2. When the number of parameters passed is the same as the number of parameters of multiple functions with duplicate names, consider the problem of parameter matching. The closest is the first, who matches the best and who calls the first

3. If there is no top priority match, find the nearest compatible match

The precondition of function overloading is that the functions must have the same name. Whether these functions are overloaded depends on the number and order of parameter types

5.3 function recursion

The first level of understanding: from the perspective of function memory operation, recursion actually refers to the function calling the function itself.

public static void main(String[] args) {
    show();
}
public static void show() {
    System.out.println("show....");
    show();
}

The show function keeps running on the stack until at some point, the stack memory is not enough, which will lead to the problem of stack memory overflow!

The second level of understanding: from the perspective of algorithm, recursion refers to the process of automatic reasoning and derivation (mathematical induction)

In the algorithm field, the two most commonly used algorithm ideas are iteration (for while loop) and recursion

public static void main(String[] args) {
    //Calculate 1 + 2 + 3 ++ Sum of 1000
    //Iterative idea O(n) linear growth
    int sum = 0;
    for (int i = 1; i <= 1000; i++) {
        sum += i;
    }
    System.out.println(sum);
    //The recursive idea O(n) grows linearly, but it will consume a certain amount of memory
    System.out.println(f(1000));
    public static int f(int x) {
        if (x == 1) {
        return 1;
    }
    return f(x - 1) + x;
}

Relatively speaking, the code written recursively is generally less than iteration, but it is difficult to understand.

public static void main(String[] args) {
    //Find the 20th item of Fibonacci sequence
    //1 1 2 3 5 8 13 21 34 55...
    // s
    // f
    // t
    //Iterative idea O(n) linear growth
    int n = 50;
    int first = 1;
    int second = 1;
    int third = 0;
    for (int i = 3; i <= n; i++) {
        third = first + second;
        first = second;    
        second = third;
    }
    System.out.println(third);
    //Recursive thought O(2^n) exponential growth
    System.out.println(f(n));
    public static int f(int x) {
    if (x == 1 || x == 2) {
        return 1;
    }
    return f(x - 1) + f(x - 2);
}

Topics: Java