Java learning notes - Methods

Posted by Domhnall on Tue, 22 Feb 2022 11:03:32 +0100

Java learning notes - Methods

Day06

1, What is 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

2, Definition of method

  • Method contains a method header and a method body.

    • **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 the method is called
    • **Method body: * * the method body contains specific statements that define the function of the method.

    Syntax: modifier return value type method name (parameter type parameter name){

    ​ ...

    Method body

    ​ ...

    Return return value;

    }

    public static void main(String[] args) {
        int max = max(10, 10);
        System.out.println(max);
    }
    
    //Specific size
    public static int max(int num1,int num2) {
    
        int result = 0;
    
        if (num1==num2) {
            System.out.println("num1==num2");
            return 0;//Termination method
        }
        if (num1>num2) {
            result = num1;
        }else {
            result = num2;
        }
    
        return result;//Return results
    }
    

3, 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 max = max(10, 10);

If the return value of the method is void, the method call must be a statement. For example, the method println returns void. The following call is a statement:

System.out.println("Hello,world!");

4, Overloading of methods

  • 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 order of parameters, 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.
public static void main(String[] args) {
        double max1 = max(10.0,30.0);
        int max2 = max(12, 56);
        System.out.println(max1);
        System.out.println(max2);
    }

    //Specific size
    public static double max(double num1,double num2) {

        double result = 0;

        if (num1==num2) {
            System.out.println("num1==num2");
            return 0;//Termination method
        }
        if (num1>num2) {
            result = num1;
        }else {
            result = num2;
        }

        return result;//Return results
    }
    //Specific size
    public static int max(int num1,int num2) {

        int result = 0;

        if (num1==num2) {
            System.out.println("num1==num2");
            return 0;//Termination method
        }
        if (num1>num2) {
            result = num1;
        }else {
            result = num2;
        }

        return result;//Return results
    }

public static void main(String[] args) {
    int add1 = add(10, 10);
    double add2 = add(12.3, 15.9);
    int add3 = add(10.1, 12.5, 15.8);
    System.out.println(add1);
    System.out.println(add2);
    System.out.println(add3);
}
public static int add (int a,int b) {
    int result = 0;
    
    result = a + b;
    
    return result;
}
public static double add (double a,double b) {
    double result = 0.0;

    result = a + b;

    return result;
}
public static int add (double a,double b,double c) {
    int result = 0;

    result = (int)a + (int)b + (int)c;

    return result;
}

I don't know why the result of add2 comes out. Finally, there is a 3 - I hope the boss can help solve it

5, Command line parameter transmission (extended understanding)

package com.kang.method;

public class Demo04 {
    public static void main(String[] args) {
        //args.length array length
        for (int i = 0; i < args.length; i++) {
            System.out.println("args[" + i + "]: "+args[i]);
        }
    }
}

There is a Terminal area under the Java compiler

Open it in the folder and complete it with the command line provided by the computer

You cannot directly run a class file. You need to find the path of the package and then load it. Otherwise, it cannot be executed, and the above error prompt appears.

6, Variable parameters (just understand)

  • JDK1. Starting from 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, and any ordinary parameter must be declared before it.
public static void main(String[] args) {
    //Call methods with variable parameters
    printMax(34,3,3,2,56.5);//Print the maximum value / / pass the variable constant parameter
    printMax(new double[]{1,2,3});   //An array was passed

}
public static void printMax( double... numbers) {
    if (numbers.length == 0) {        //Judge whether the passed parameter is equal to 0
        System.out.println("No argument passed");   //If it is equal to 0, it is equivalent to no parameter passed, and "No argument passed" will be printed
        return;
    }

    double result = numbers[0];   //Defines a return value. result is an array

    //Sort!
    for (int i = 1; i < numbers.length; i++) {
        if (numbers[i] >result) {
            result = numbers[i];
        }
    }
    System.out.println("The max value is " + result);
}

7, Recursion

  • Call method A

  • Recursion is: method A calls method A by itself! 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 to call its own method.
//recursive thinking 
public static void main(String[] args) {
    System.out.println(f(5));
}
//5! 5*4*3*2*1
public static int f (int n) {

    if (n==1) {
        return 1;
    }else {
        return n*f(n-1);
    }
}

8, Chapter practice

Write a calculator, which is required to realize the function of addition, subtraction, multiplication and division, and can receive new data circularly, which can be realized through user interaction

Click the link to view

Online learning recommendation: Crazy God says Java

Website self-study recommendation: Rookie tutorial | Java Tutorial

Topics: Java