Home  >  Article  >  Java  >  Java method usage example analysis

Java method usage example analysis

PHPz
PHPzforward
2023-04-19 16:52:06625browse

1. The concept of method and its use

1.1. What is a method

A method is a code fragment. It is similar to a "function" in C language. The functions are as follows:

1. It is able to organize the code in a modular manner (when the code size is relatively complex).

2. It allows the code to be reused, and one code can be used in multiple Position usage.

3. Make the code easier to understand and simpler.

4. Directly call existing methods for development without reinventing the wheel.

1.2. Definition of methods

Definition format:

Java method usage example analysis

Example: Write a function to find the sum of factorials of several terms

public class TeseDemo220424 {
//    计算某一个数的阶乘
    public static int func(int n){
        int ret = 1;
        for(int i = 1;i <= n;i++){
            ret *= i;
        }
        return ret;
    }
//    计算前多少项阶乘之和
    public static int func1(int k){
        int sum = 0;
        for(int i = 1;i <= k;i++){
            sum += func(i);
        }
        return sum;
    }
    public static void main(String[] args) {
//        写函数来求阶乘之和
        Scanner myscanner = new Scanner(System.in);
        System.out.println("请输入你想要求取前多少项的阶乘的和:");
        int num = myscanner.nextInt();
        int sum = func1(num);
        System.out.println("前 " + num + "项的阶乘和为" + sum);
    }
}

Note:

1. Modifier: At this stage, the public static fixed combination is directly used (because the main method is public static, so only static methods can be called in it).

2. Return value type: If the method has a return value, the return value type must be consistent with the returned entity type. If there is no return value, it must be written as void.

3. Method name: Use small camel case for naming.

4. Parameter list: If the method has no parameters, write nothing in (). If there are parameters, the parameter type needs to be specified. Use commas to separate multiple parameters.

5. Method body: the statement to be executed inside the method.

6. In java, methods must be written in classes.

7. In java, methods cannot be nested.

8. In java, there is no method declaration. (Declaration and definition are not distinguished)

1.3. Execution process of method calling

Calling process:

Call method—>Pass parameters—>Find the method address —>The method body that executes the called method—>The called method ends and returns—>Return to the main calling method to continue execution

Image:

Java method usage example analysis

Note:

1. When a method is defined, the code of the method will not be executed. It will only be executed when it is called.

2. A method can be Called multiple times.

1.4. The relationship between actual parameters and formal parameters (important)

Everyone is certainly familiar with the relationship between formal parameters and actual parameters, that is, the formal parameters are part of the actual parameters. A temporary copy is made, which means that changes to the formal parameters will not affect the actual parameters.

Illustration of specific reasons: (Because the specific issues related to function stack frames are more complicated, here is a brief explanation for you)

Java method usage example analysis

So, As can be seen from the figure, when calling by value, the values ​​of the formal parameters and actual parameters are not stored in the same space at all, so they will not interfere with each other. In C language, if you want the change of the formal parameters to affect the actual parameters , then it must be a call by address, but there is no such thing as call by address in Java. The solution can only be to use references (which will be introduced in detail later).

2. Method overloading

2.1. Why method overloading is needed

public class TestDemo220426 {
    public static int addInt(int x,int y){
        return x + y;
    }
    public static double addDouble(double x,double y){
        return x + y;
    }
    public static void main(String[] args) {
        int a = 10;
        int b = 10;
        int ret = addInt(a,b);

        double c = 11.1;
        double d = 12.1;
        double ret1 = addDouble(c,d);
    }
}

Look at this code, the two methods addint and adddouble are both for the purpose of The sum of two numbers, but you have to define two different functions with different function names, but sometimes naming is a headache, so since the essential functions of the methods are the same, the parameters may be different, So can we all use the same function name?

The answer is yes, and this is called method overloading.

2.2. Definition of method overloading

In Java, if multiple methods have the same name and different parameter lists, they are said to be overloaded. That is, the same name but with different meanings.

public class TestDemo220426 {
    public static int add(int x,int y){
        return x + y;
    }
    public static double add(double x,double y){
        return x + y;
    }
    public static void main(String[] args) {
        int a = 10;
        int b = 10;
        int ret = add(a,b);
        System.out.println(ret);
        double c = 11.1;
        double d = 12.1;
        double ret1 = add(c,d);
        System.out.println(ret1);
    }
}

Screenshot of program running:

Java method usage example analysis

It can be seen from the above program that they all implement the addition function, but they define two different Function implementation, just the function name is the same, this is function overloading. The compiler will call the corresponding function based on the parameters you pass in.

Note:

1. The method names must be the same.

2. The parameter list must be different (the number of parameters is different, the types of parameters are different, and the order of types must be different) (need to be distinguished by parameters)

3. Is it the same as the return value type? The same is irrelevant

4. You cannot define two functions that are only distinguished by their return values. This cannot constitute overloading

5. When the compiler compiles the code, it will deduce the actual parameter types. Determine which method to call based on the results of the deduction

2.3. Method signature

The method signature is: the final name of the method after being compiled and modified by the compiler. The specific method is: the full path name of the method, parameter list, and return value type, which constitute the complete name of the method. Used to distinguish overloaded functions

How can we view our method signatures:

1. First compile the project to generate a .class bytecode file

2. In the console, enter the directory where the .class you want to view is located

3. Enter: javap -v bytecode file name

3. Recursion

3.1. The concept of recursion

Definition: A method that calls itself during execution is called "recursion."

Necessary conditions for recursion:

1. Recursive formula.

2. Recursive termination condition.

3.2、递归过程分析

    public static  int func(int num){
        if(num == 1){
            return 1;
        }
        return num*func(num - 1);
    }
    public static void main(String[] args) {
//        递归求阶乘
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入一个数:");
        int num = scan.nextInt();
        int ret = func(num);
        System.out.println("阶乘为:" + ret);
    }
}

在这里我们以求一个数的阶乘的代码为例来分析一个递归的过程:

Java method usage example analysis

递归的过程其实不复杂,看成两个部分,一个是递出去,而是归回来,上面的蓝色箭头是递的过程,红色箭头是归的过程。

3.3、递归小练习

  • 按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4)

public class TestDemo220427 {
    public static void myprint(int num){
        if(num < 10){
            System.out.println(num%10);
            return;
        }
        myprint(num/10);
        System.out.println(num%10);
        return;
    }
    public static void main(String[] args) {
//        递归实现按顺序打印数字的每一位
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入一个数:");
        int num = scan.nextInt();
        myprint(num);
    }
}
  • 求斐波那契数列的第 N 项

public class TestDemo220428 {
    public static int fib1(int n){
        int f1 = 1;
        int f2 = 1;
        int f3 = 1;
        for(int i = 3;i <= n;i++){
            f3 = f1 + f2;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }
    public static int fib(int n){
        if(n == 1 || n == 2){
            return 1;
        }
        return fib(n-1) + fib(n-2);
    }
    public static void main(String[] args) {
//        递归求斐波那契数列的第n项
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入您想要求取的项数:");
        int n = scan.nextInt();
        int ret = fib1(n);
        System.out.println("第" + n + "项为:" + ret);
    }
}

利用递归求斐波那契数列的第n项的话,其实是一个双路递归,不推荐这种求解的方法,因为会算很多重复的项,效率很低,一般都是选择循环迭代的方式来生成斐波那契数即可。

Java method usage example analysis

The above is the detailed content of Java method usage example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete