This is the 20th day of my participation in the Novembermore Challenge.The final text challenge in 2021″@TOC

@TOC

One, foreword

See the title, some students may be strange, ah. How is a method, I previously learned C language, is not called a function, to Java how to become a method. In fact, the two are the same, if you want to be literal, methods can’t exist without classes, and functions can.

Two, the basic concept of the method

2.1 What is method

A method, which can be understood as a C function, is a snippet of code that performs or completes a task.

2.2 Creating a method

In Java, the format for creating a method is:

Method return type + method name (parameter type) {method body}Copy the code

For example: I need to create a method that adds two numbers!

  int  add(int a,int b){
  return a+b;
  }
Copy the code

Here,int is the method return type, add is the method name,int a,int b are the type and parameter names of the method parameters. Return a + b. Is the method body. If the method return type is not void, at the end of the method, you need to return the method return type. The method returns an int at the end of the method.

Method overloading

3.1 overloading

In short, providing different versions of the same method name is called overloading.

Rules for overloading:

  • Same method name
  • Different method parameters (either number of parameters or type of parameters)
  • Method return value type does not affect overloading
  • An overload does not occur when two methods have the same name and the same parameters but return different values.

Error demonstration of method overloading:

public static int addInt(int x, int y) {
 return x + y;
 }
Copy the code
public static double addDouble(int x, int y) {
 return x + y;
 }
Copy the code

So what’s wrong with addInt is that it’s not an int, it’s a double.

4. Recursion of methods

The act of a function calling itself is called recursion of a method. Here’s an example:

Take N factorial

public static int factor(int n) {
    if (n == 1) {
        return 1;
   }
    return n * factor(n - 1); 
}
Copy the code

Like return n * factor(n-1); Code like this. The recursion of the method is when the factor method calls its own behavior in the method body.