Java small test chopper - the use of methods

1 Introduction

In this blog, let's learn about the methods in Java together. In fact, they are very similar to the functions in C language, but there are also some unique features of Java. Let's start today's blog journey together.

2. Method concept and use

2.1 What is a method

A method is a code fragment. It is similar to a "function" in C language . The significance of the method's existence:

  1. It is able to organize the code modularly (when the code size is more complex).
  2. So that the code is reused, a code can be used in multiple places.
  3. Make the code easier to understand and easier.
  4. Directly invoke existing method development without reinventing the wheel.
  • For example: to develop a calendar now, in the calendar, it is often necessary to judge whether a year is a leap year, then there is the following code:
int year = 1900;
if((0 == year % 4 && 0 != year % 100) || 0 == year % 400){
    System.out.println(year+"年是闰年");
    }else{
        System.out.println(year+"年不是闰年");
    }

How should the method be defined?

2.2 Method Definition

2.2.1 Method Syntax Format

// method definition
modifier return value type method name ([parameter type parameter...]) {         method body code;         [ return return value]; }


  •  Example 1: Implement a function to detect whether a year is a leap year.
public class Method{
// 方法定义
public static boolean isLeapYear(int year){
    if((0 == year % 4 && 0 != year % 100) || 0 == year % 400){
        return true;
    }else{
            return false;
    }
}
}
  • Example 2: Implement a method to add two integers.
public class Method{
// 方法的定义
    public static int add(int x, int y) {
    return x + y;
    }
}

2.2.2 Precautions

  1. Modifier: At this stage, directly use public static fixed collocation.
  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: Named with a small camel case, for example: isPrime.
  4. Parameter list: If the method has no parameters, write nothing in (). If there are parameters, you need to specify the parameter type, and 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; methods cannot be nested; there is no method declaration.

2.3 Execution process of method call

2.3.1 Method call process

  • Call method ---> Pass parameters ---> Find the method address ---> Execute the method body of the called method ---> The called method ends and returns ---> Return to the calling method and continue to execute. In fact, it is similar to calling functions in C language.

2.3.2 Precautions

  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.

2.3.3 Code example

  • Code Example 1: Computing the Addition of Two Integers
public class Method {
public static void main(String[] args) {
    int a = 10;
    int b = 20;
    System.out.println("第一次调用方法之前");
    int ret = add(a, b);
    System.out.println("第一次调用方法之后");
    System.out.println("ret = " + ret);
    System.out.println("第二次调用方法之前");
    ret = add(30, 50);
    System.out.println("第二次调用方法之后");
    System.out.println("ret = " + ret);
}
public static int add(int x, int y) {
    System.out.println("调用方法中 x = " + x + " y = " + y);
    return x + y;
}
}
// 执行结果
一次调用方法之前
调用方法中 x = 10 y = 20
第一次调用方法之后
ret = 30
第二次调用方法之前
调用方法中 x = 30 y = 50
第二次调用方法之后
ret = 80

Code Example 2: Calculate 1! + 2! + 3! + 4! + 5!

public class TestMethod {
public static void main(String[] args) {
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        sum += fac(i);
    }
    System.out.println("sum = " + sum);
}
public static int fac(int n) {
    System.out.println("计算 n 的阶乘中n! = " + n);
    int result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}
}
// 执行结果
计算 n 的阶乘中 n! = 1
计算 n 的阶乘中 n! = 2
计算 n 的阶乘中 n! = 3
计算 n 的阶乘中 n! = 4
计算 n 的阶乘中 n! = 5
sum = 153

2.4 The relationship between actual parameters and formal parameters (important)

  • The formal parameters of a method are equivalent to the arguments in a mathematical function.
  • The formal parameter of the method in Java is equivalent to the argument n in the sum function, which is used to receive the value passed by the sum function when it is called. The name of the formal parameter can be chosen arbitrarily, and has no effect on the method . The formal parameter is just a variable that the method needs to use when it is defined, and is used to save the value passed when the method is called.
  • The formal parameter is a temporary copy of the actual parameter. When {} ends, its life cycle ends .
  • In the memory, the actual parameters in the main method and the formal parameters in other methods are opened up separately . When the own program ends, the created space is automatically returned to the memory , so the change of the formal parameters will not affect the actual parameters. .
  • There is no concept of addressing (calling) in Java , because we cannot get the address of the actual parameter.
  • Code 1:
public static int getSum(int N){ // N是形参
    return (1+N)*N / 2;
}
getSum(10); // 10是实参,在方法调用时,形参N用来保存10
getSum(100); // 100是实参,在方法调用时,形参N用来保存100
  • Code 2:
public static int add(int a, int b){
    return a + b;
}
add(2, 3); // 2和3是实参,在调用时传给形参a和b
  •  Code 3:
public class TestMethod {
public static void main(String[] args) {
    int a = 10;
    int b = 20;
    swap(a, b);
    System.out.println("main: a = " + a + " b = " + b);
}
public static void swap(int x, int y) {
    int tmp = x;
    x = y;
    y = tmp;
    System.out.println("swap: x = " + x + " y = " + y);
}
}
// 运行结果
swap: x = 20 y = 10
main: a = 10 b = 20
  • It can be seen that after the swap function is exchanged, the values ​​of the formal parameters x and y have changed, but in the main method, a and b are still the values ​​before the exchange, that is, the exchange is not successful, and the change of the formal parameters does not affect the actual parameters .
  • Cause Analysis:
  1. The actual parameters a and b are two variables in the main method, and their space is in the stack (a special memory space) of the main method, while the formal parameters x and y are two variables in the swap method, the space of x and y In the stack when the swap method is running, therefore: the actual parameters a and b and the formal parameters x and y are two unrelated variables .
  2. When the swap method is called, only the values ​​in the actual parameters a and b are copied and passed to the formal parameters x and y, so the operation on the formal parameters x and y will not have any impact on the actual parameters a and b .
  • Note : For the basic type, the formal parameter is equivalent to the copy of the actual parameter, that is, call by value.
  • Solution: pass reference type parameters (such as arrays to solve this problem):
public class TestMethod {
public static void main(String[] args) {
    int[] arr = {10, 20};
    swap(arr);
    System.out.println("arr[0] = " + arr[0] + " arr[1] = " + arr[1]);
}
public static void swap(int[] arr) {
    int tmp = arr[0];
    arr[0] = arr[1];
    arr[1] = tmp;
}
}
// 运行结果
arr[0] = 20 arr[1] = 10

2.5 Methods with no return value

  • The return value of the method is optional. Sometimes it can be absent, and when there is no return value type, it must be written as void.
class Test {
public static void main(String[] args) {
    int a = 10;
    int b = 20;
    print(a, b);
}
public static void print(int x, int y) {
    System.out.println("x = " + x + " y = " + y);
}
}

3. Method overloading

3.1 Why method overloading is needed

  • There is the following code:
public class TestMethod {
public static void main(String[] args) {
    int a = 10;
    int b = 20;
    int ret = add(a, b);
    System.out.println("ret = " + ret);
    double a2 = 10.5;
    double b2 = 20.5;
    double ret2 = add(a2, b2);
    System.out.println("ret2 = " + ret2);
}
public static int add(int x, int y) {
    return x + y;
}
}
// 编译出错
Test.java:13: 错误: 不兼容的类型: 从double转换到int可能会有损失
double ret2 = add(a2, b2);
  • Because the parameter types do not match, the existing add method cannot be used directly. A relatively simple and crude solution is to write another code that can achieve the same function but with different parameters, as follows:
public class TestMethod {
public static void main(String[] args) {
    int a = 10;
    int b = 20;
    int ret = addInt(a, b);
    System.out.println("ret = " + ret);
    double a2 = 10.5;
    double b2 = 20.5;
    double ret2 = addDouble(a2, b2);
    System.out.println("ret2 = " + ret2);
}
public static int addInt(int x, int y) {
    return x + y;
}
public static double addDouble(double x, double y) {
    return x + y;
}
}
  • The above code can indeed solve the problem, but the unfriendly part is that many different method names need to be provided, and choosing a name is a headache. Can all the names be given as add? But the parameters inside can be different types and different numbers of parameters. This is the method overloading function.

3.2 Method overloading concept

  1. In natural language, if a word has multiple meanings, it is said that the word is overloaded, and what meaning it represents needs to be combined with a specific scene.
  2. Methods can also be overloaded in Java.
  3. In Java, if multiple methods have the same name but different parameter lists, the methods are said to be overloaded .
public class TestMethod {
public static void main(String[] args) {
    add(1, 2); // 调用add(int, int)
    add(1.5, 2.5); // 调用add(double, double)
    add(1.5, 2.5, 3.5); // 调用add(double, double, double)
}
public static int add(int x, int y) {
return x + y;
}
public static double add(double x, double y) {
    return x + y;
}
public static double add(double x, double y, double z) {
    return x + y + z;
}
}
  • All add in it is called method overloading.
  • Notice:
  1. The method names must be the same.
  2. The parameter lists must be different ( the number of parameters is different, the types of parameters are different, and the order of types must be different ), and one or several of them are different.
  3. It doesn't matter if the return type is the same or not .
  4. Two methods cannot be overloaded just because the return value type is different.
// 注意:两个方法如果仅仅只是因为返回值类型不同,是不能构成重载的
public class TestMethod {
public static void main(String[] args) {
    int a = 10;
    int b = 20;
    int ret = add(a, b);
    System.out.println("ret = " + ret);
}
public static int add(int x, int y) {
    return x + y;
}
public static double add(int x, int y) {
    return x + y;
}
}
// 编译出错
Test.java:13: 错误: 已在类 Test中定义了方法 add(int,int)
public static double add(int x, int y) {
^
1 个错误
  • When the compiler compiles the code, it deduces the actual parameter type, and determines which method to call according to the deduction result.

4. Conclusion

In this blog, we focused on explaining the definition and use of methods in Java. Finally, we also introduced what method overloading is. I hope everyone can gain something.

Guess you like

Origin blog.csdn.net/weixin_44580000/article/details/124451606