Java Foundation: programming always needs some "methods" ~ let me tell you what methods are today

Keywords: Java Back-end

Method function

There are functions when you come into contact with the first program in Java. The main function is a function that specifies the writing method in Java: the main function is usually written in an open class, and the code in the main function is automatically generated when executing a java program.

Definition of function:

Functions are code blocks written in classes with certain special functions. Functions can be defined by themselves, but the main function will be automatically scanned and run by the interpreter. Customized functions need to be called manually.

Meaning of function:

Functions actually exist to make code reusable. For example, if you write the program for addition operation into a separate function, you only need to call this function when using addition operation, without rewriting a new addition algorithm. This is called code reusability, that is, the reuse of a set of code.

When all addition operations use the same set of addition codes, if there are special changes in the addition algorithm, only the content of the addition function needs to be changed, and the location of other calls will automatically update the algorithm due to the update of the addition function, so as to realize the unification of standards and facilitate maintenance and change.

Function design principle:

Because the meaning of function is to make the code reuse to the greatest extent, and it is convenient to maintain and improve the algorithm. The concept of "high cohesion and low coupling" should be considered when designing the method.

Cohesion can be simply understood as the degree of concentration in doing one thing, and coupling represents the cascade impact of doing one thing on other things. High cohesion can be understood as being extremely specific to what you are doing. Low coupling means that your changes will not have too much impact on too many modules.

For example, if you want to do a set of login functions, if you concentrate all the code in one method, any maintenance or change in any step will test the whole method or lead to the collapse of the whole process. If these functions such as input, verification, display and so on are isolated, these methods are invoked in the running process of the login process. The verification of a function can be realized during development and testing, and the failure of a function will not affect other modules, and the troubleshooting and maintenance is simpler.

To what extent can the process code be split to achieve the most perfect high cohesion and low coupling, which involves the granularity of the business. If the splitting is too detailed, it will lead to difficult maintenance and complex code, but if the splitting is too coarse, it will violate the principle of high cohesion and low coupling. In fact, each project and process should have its own business granularity, which means different splitting fineness. This needs to be studied with reference to the strength of the whole system and more professional knowledge.

Declarative function

Declaration is to create a user-defined function. You can refer to each part of the main function to design your own function structure:

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

Referring to the structure of the main function, you can get the syntax of creating the function:

Modifier return value type custom function name(Parameter table){
    Code in method body
}

There are three necessary parts for designing a function: method name, return value type and parameter table. The following is an example of the simplest method declaration, but it cannot be executed. Similar functions will be seen in future knowledge:

void fun();

If you want to design a function that can run, you can modify it slightly on the basis of the main function:

public static void hello(){
	System.out.print("in hello!");
}

The specific content is the same as the explanation of each part of the main function. See the first program chapter. Methods are written to the class. If there is a main function in the class, the contents of the whole java file should be as follows:

public class Index{
    public static void main(String[] args){
        System.out.println("helloworld!");
    }
    public static void hello(){
        System.out.print("in hello!");
    }
}

The creation of the first method has many words that do not understand the meaning and many theories that have not been explained. You can understand the meaning after learning deeper knowledge in the future.

At present, the code can be temporarily written as an example for the main purpose of running successfully.

Call function

Except for the main function, any custom function must be called manually to execute. Call is to execute the contents of the function, and use an instruction to complete the call to the function. This instruction is usually written in the main function and other functions:

Object or class name.Function name(Parameter table);

The function name is also the name of the user-defined function. The parameter table will be described below. As for the object or class name in front of the function name, you will know its principle after learning object-oriented. In the initial function learning stage, you can ignore all the contents in front of the function name. The call to a user-defined function is as follows:

public static void main(String[] args){
    System.out.print("test hello!");
    hello2();//call
}
public static void hello1(){//statement
    System.out.print("in hello!");
}

In the beginning process, the main function is usually used to trigger the call to the method, so the call statement is usually written in the main function. But in fact, in the future development process, it is more often the call between methods:

public static void main(String[] args){
    System.out.println("test hello!");		//1
    hello1();//call 							// two
    System.out.println("test hello end!");	//7
}

public static void hello1(){//statement
    System.out.println("in hello1!");		//3
    hello2();//call 							// four
    System.out.println("hello1 end!");		//6
}

public static void hello2(){//statement
    System.out.println("in hello2!");		//5
}

Parameters and return

In addition to the method body wrapped in braces, the method name, parameter table, return value and modifier are called the signature of the method. Modifiers usually refer to the access scope of the method and the type of the method, which will be learned in the future.

When using a method, the following three points should be clear:

  1. What is the specific function of this method.
  2. What parameters are required to start this method.
  3. What data can be obtained after the execution of this method.

In fact, in order to make the program easier to read and use, the above three views will be marked in the way of document annotation.

Parameter table

The parameter table represents the values required for the start of the method and the types of values. Parameters can be multiple and can be of any type. When calling a method, you must pass in the parameters required by the method. These parameters can only be used in the method body as local variables.

In the parameter table of the declared method, you need to declare the parameter type and the parameter name used in the method. Because the parameter declaration does not have an actual value, it is only a formal parameter, which needs to be assigned during the call, which is called a formal parameter.

When calling a method, you only need to pass in the specified number and type of values at the specified position in the parameter table. These values will be assigned to formal parameters before the method is started, so they are called arguments.

Formal parameters and arguments can also be assigned using automatic type promotion.

public static void main(String[] args){
    // Call the same method and get different results through different parameters
    add(1,1.0);
    add(2,2.0);
    add(3,3.0);
}

public static void add(int a,double b){
    System.out.println(a+b);//Direct output of parameter addition results
}

The String[] args of the main function is actually a formal parameter, because the caller is a Java interpreter, and the parameters passed in are usually passed in the console. That is, String [] is the type of args, and args is actually a variable name. Although the declaration of formal parameter variables can be customized, it is still recommended to use the official JAVA recommended writing args.

Return value

The location of the calling method. The value can be obtained by calling this method, and the return value type indicates what type of value can be obtained by calling this method. This value can be an operation result or a value of any meaning, depending on the actual meaning of the method. However, as long as the return value type of the method is specified, the method must return a value of the specified type.

void means that this method does not have any return value, so it cannot return any value in the method body.

Return keyword is used to terminate the method and return the value to the calling position of the method. The value carried will be assigned to the variable through the calling statement of the method:

// Call the method to pass in two values and get the result after adding the two values
public static void main(String[] args){
    int i = 10;
    double j = 11.11;

    double h = addNumber(i,j);//The values of i and j are passed here
    System.out.print(h);
}


public static double addNumber(int a,double b){
    double c = a+b;
    return c;//The value of c is returned here
}

In a method, the return statement is usually written to the end of the method. Of course, it can also be returned in the middle of method execution. If the method returns, the execution of the method will be terminated, which means that all statements after the return statement can never be executed, and an error will be reported in the compilation.

However, you can selectively terminate the method by writing multiple return s through the process control statement. Because Java believes that any if statement may not be executed, there will be no code error that can never be executed during compilation:

public static double addNumber(int a,double b){
    double c = a+b;

    /*
	java I think that all if code blocks may not be executed.
	So "if the method declares the return value type, but the return statement is in if, there must be a guaranteed return under if"!
	If the if code block is executed, the guaranteed return is not executed; otherwise, the guaranteed return is executed.
    */
    if(c >= 100){
        return c;//The value of c is returned here
    }
    return 0;
    
    //The following code: execute else without executing if, and return on the contrary. java believes that this program must return content, so it is legal.
    if(c >= 100){
        return c;//The value of c is returned here
    }else{
        return 0;
    }
    
    //The first writing method is recommended
}

Reasonable use of branch statements to control the return of methods can reduce the amount of code and make the process clear and easy to read. For example, there are multiple branch conditions in a method that can return results. Usually, continuous if else will be used, but in fact, as long as you enter an if code block, you will not execute other code blocks. Then use a separate if statement and add a return statement. Similarly, stop the method after entering a code block, and you will not enter other code blocks:

public static double addNumber(int a,double b){
    double c = a+b;
	
    //The following two return processes are the same! The second one is recommended!
    
    //Return data using if else coherence
    if(c >= 100){
        return c;
    }else if(c>=200){
        return 0;
    }else if(c>=300){
        return 1;
    }else{
        return 2;
    }
    
}

After the above code is modified, it can be written as follows:

public static double addNumber(int a,double b){
    double c = a+b;
    //Use if to return (recommended)
    if(c >= 100){
        return c;
    }
    if(c>=200){
        return 0;
    }
    if(c>=300){
        return 1;
    }
    return 2;
}

The coordination optimization of return statement and if statement can be studied and explored in the project reconstruction stage after mastering the basic knowledge.

Recursive call

If you call yourself in a method, such syntax is allowed, but if the program is running, the call of the method will be nested continuously and progressively. The necessary conditions exist to enable the method to end the progression. Usually, it will carry parameters back layer by layer. This writing method is called recursion.

Recursion can realize functions similar to loops, but recursion will occupy stack space. Too many recursion layers will lead to stack space overflow. Too many loops will produce too many useless variables or objects, which mostly occupy large heap space. Using loops is safer than using recursion.

Recursion is used to return the execution result of the inner layer method to the upper layer until it is returned to the position of the first layer method call to display the result. Using this feature, the Fibonacci sequence of specified length can be obtained:

//The Fibonacci value is obtained recursively. The passed in value represents the first + 1 Fibonacci value, and the returned value refers to the value on the location.
public static int Fibonacci(int n) {
    if(n == 0)
        return 0;
    if(n == 1)
        return 1;
    return Fibonacci(n-2) + Fibonacci(n-1);
}

Posted by wee493 on Sun, 21 Nov 2021 12:18:28 -0800