Day08 Java method

Java method

I 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

II Principles of design method

  • The original meaning of method is function block, which is the collection of statement blocks to realize a 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.
  • Naming rules of the method: small hump principle.

III Definition of method

  • In general, a method used to complete a function in a specific Java language contains a fragment of code similar to the following:

  • 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 the method is called, the value is passed to the parameter. 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.

      The definition format is as follows

    Modifier return value type method name(Parameter type, parameter name, ...) {
        //Method body
        return Return value;
        //If the return value type is void, the return value is not required
        //The return keyword can also be used as a process control method, which ends directly after the return statement is executed,
    }
    

IV 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!");
    

    Expand your understanding after class: value passing (Java) and reference passing

V Overloading of methods

  • Overloading is a function with the same function name but different formal parameters in a class.

  • Rules for method overloading:

    • Method names must be the same.
    • The parameter list must be different (different number, type, parameter order, etc.) and the return type of the method can be the same or different.
    • Just different return types are not enough to overload methods.
  • Implementation 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.

Vi 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 the specified 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.

    public class VariableMethod {
        public static void main(String[] args) {
            double [] numbers = {3, 5, 1, 2, 4};
            double res = max(numbers);
            if ( -1 == res) System.out.println("Empty array!");
            else System.out.println("Max number: " + res);
        }
    
        //Variable parameter function
        //Suppose there are only positive numbers
        public static double max (double... d) {
            if ( 0 == d.length) return -1;
    
            //Get max number
            double res = d[0];
            for (int i = 0; i < d.length; i++) {
                if ( 0 > res - d[i] ) res = d[i];
            }
            return res;
        }
    
    }
    //This example uses an array, just to help understand, and there is no need to delve into the problem for the time being
    

VII recursion

  • Recursion is A method that calls itself. For example, A method A that calls method A is recursive.

  • 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 to call its own method.
  • Although recursion is concise, it will bring huge performance overhead. Try to avoid using recursion when a large number of calculations are required. Here is an example of using recursion to calculate factorial:

    public class Factorial {
        public static void main(String[] args) {
            System.out.println("10! = " + factorial(10));  //Output 3628800
        }
    
        //Use recursion to calculate 10 factorials
        //You can experiment with what happens when the calculated number is large
        public static int factorial(int n) {
            if ( 1 == n ) {
                return  1;
            } else {
                return n * factorial(n-1);
            }
        }
    }
    

Posted by uglyrat on Sun, 17 Apr 2022 05:01:35 +0930