Detailed explanation of Java methods

What is the method

Java methods are collections 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

Method definition and call

Definition of method

Basic definition:

Modifier return value type method name(Parameter type parameter name){
    ------
    Method body
    ------
    return Return value;
}

How to compare data sizes:

public class Demo01 {
    public static void main(String[] args) {
        int max = max(10,20);
        System.out.println(max);
    }
    public static int max(int a,int b){
        int result = 0;
        if(a==b){
            System.out.println("a==b");
            return 0;//Termination procedure
        }
        if(a>b){
            result = a;
        }else{
            result = b;
        }
        return result;
    }
}

Method call

Calling method: object name Method name (argument list)

Java supports two methods of calling methods, which are selected according to whether the method has a return value

  • When a method returns a value, the method call is usually regarded as a value, for example:

    int max = max(10,20);
    
  • When the return value of the method is void, the method call must be a statement, for example:

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

Value passing and reference passing

pass by value refers to copying and passing a copy of the actual parameters to the function when calling the function, so that if the parameters are modified in the function, the actual parameters will not be affected.
pass by reference refers to directly passing the address of the actual parameter to the function when calling the function. The modification of the parameter in the function will affect the actual parameter.

Take a simple example:

You have a key. When your friend wants to go to your house, if you give him your key directly, this is citation transmission. In this case, if he does something to the key, for example, he engraves his name on the key, when the key is returned to you, his engraved name will be added to your own key.

You have a key. When your friend wants to go to your house, you engrave a new key to him, and your own is still in your hand. This is value transmission. In this case, nothing he does to the key will affect the key in your hand.

In Java, value is actually passed, but for object parameters, the content of the value is the reference of the object.

Method overload

What is overloading

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

public static double max(double a,double b){---}
public static int max(int a,int b){---}
public static int max(int a,int b,int c){---}
public static int max(int b,int a){---}

Rules for overloading methods

  • Method names must be the same
  • The parameter list must be different (different number, different types, 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 them 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.

Command line pass parameters

Sometimes you want to pass messages to a program when it runs, which depends on passing command-line parameters to the main() function.

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

Variable parameters

  • 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 specified parameter can be declared in a method. It must be the last parameter of the method. Any ordinary parameter must be declared before it.
public class Demo03 {
    public static void main(String[] args) {
        //Calling methods with variable parameters
        printMax(...numbers:10,20,30,40,50,60);
        printMax(new double[]{1,2,3});
    }
    public static void printMax(double...nubmers){
        if(numbers.length = 0){
            System.out.println("No argument passed");
            return;
        }
        double result = numbers[0];
        //Sort!
        for (int i = 0; i < nubmers.length; i++) {
            if (numbers[i] > result){
                result = nubmers[i];
            }
        }
        System.out.println("The max vaule is" + result);
    }
}

recursion

The recursive structure consists of two parts:

  • Recursive header: when not to call its own method. If not, the head will fall into the loop.
  • Recursive body: when to call its own method.

Example: calculating factorials

public class Demo04 {
    public static void main(String[] args) {
        System.out.println(f(5));
    }
    public static int f(int n){
        if(n==1){
            return 1;
        }else{
            return n * f(n-1);
        }
    }
}

Exercise: simple calculator

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

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String isNext = "Yes";
        while (isNext.equals("Yes")){
            System.out.println("Please select the calculation method: 1.Add 2.Subtraction 3.Multiplication 4.division");
            int s = scanner.nextInt();
            System.out.println("Please enter the calculated variable:");
            double x = scanner.nextDouble();
            double y = scanner.nextDouble();
            double result;
            switch(s){
                case 1:
                    result=plus(x,y);
                    System.out.println("The result of the calculation is"+x+"+"+y+"="+result);
                    break;
                case 2:
                    result=subtract(x,y);
                    System.out.println("The result of the calculation is"+x+"-"+y+"="+result);
                    break;
                case 3:
                    result=multiply(x,y);
                    System.out.println("The result of the calculation is"+x+"*"+y+"="+result);
                    break;
                case 4:
                    if (y==0){
                        System.out.println("Divisor cannot be 0!");
                    }else{
                        result=divide(x,y);
                        System.out.println("The result of the calculation is"+x+"/"+y+"="+result);
                    }
                    break;
                default:
                    System.out.println("Input operator error!");
                    break;
            }
            System.out.println("Continue calculation?(input Yes Continue, any other key ends): ");
            isNext=scanner.next();//Termination conditions
        }
        System.out.println("Thanks for using this calculator!");
        scanner.close();
    }
    public static double plus(double a,double b){
        return a+b;
    }
    public static double subtract(double a,double b){
        return a-b;
    }
    public static double multiply(double a,double b){
        return a*b;
    }
    public static double divide(double a,double b){
        return a/b;
    }
}

Keywords: Java

Added by anonymouse on Sun, 02 Jan 2022 20:45:01 +0200