From Beginner to Expert: A Complete Guide to the Java Method

Table of contents

1. The concept and use of the method

1.1 What is a method

1.2 Definition of method

1.3 method call

 1.4 The relationship between actual parameters and formal parameters

1.5 Methods with no return value

1.6 Significance of the method 

2. Method overloading

2.1 Implementation of method overloading

2.2 Significance of method overloading

2.3 Method signature


 

 

1. The concept and use of the method

1.1 What is a method

A method is a code fragment . It is similar to a " function" in the C language to achieve a specific function. We enter the relevant code into the method and let the method complete the function for us. It involves method definition, invocation, and execution.

To give a few simple examples:

  1. Cooking Food: Compare cooking food to a method. You have a recipe (method definition) which contains the steps to cook a particular dish. When you want to cook the same dish, you can prepare the ingredients, cook them according to the instructions of the recipe (calling the method), and finally get a delicious dish.

  2. Call: Compare a call to a method. When you want to talk to someone, you enter their phone number (method parameter) and press the dial key (call method). The telephone network connects you to each other, and you can communicate and pass on messages.

  3. Laundry: Compare laundry to a method. When you need to wash laundry, you put the laundry in the washing machine (method parameter), select the appropriate program and detergent (method call), and start the washing machine (execute method). In the end, you will have clean laundry.

In these examples, methods provide a reusable way to perform specific tasks. They take input (parameters), perform a sequence of operations, and produce output (results). Such abstractions allow us to organize and reuse our actions more efficiently, just like using methods in programming.


1.2 Definition of method

A method definition consists of the following components:

  1. Access modifier (Access Modifier) : Used to control whether other classes can access the method. Common access modifiers include public, private, protected, and default (uses no modifiers).

  2. Return Type (Return Type) : Specify the data type returned after the method is executed. If the method does not return any value, the keyword void can be used.

  3. Method Name (Method Name) : The name used to uniquely identify the method. Method names should be descriptive and clearly express the function of the method.

  4. Parameter List (Parameter List) : Specifies the input parameters accepted by the method. Parameters are the data required for method execution, there can be multiple parameters, and each parameter has its data type and name.

  5. Method Body : Contains the actual code block that defines the operations to be performed by the method. The method body is surrounded by a pair of curly braces {}, which contains a series of statements and logic.

  6. Return Statement : If a method has a return type, it can use a return statement to return the result to the caller. The return statement can also terminate the execution of a method prematurely.

Implemented in code block like this:

// 方法定义
修饰符 返回值类型 方法名称([参数类型 形参 ...]){
方法体代码;
[return 返回值];
}

For example a simple code:

public int Sum(int num1, int num2) {
        int sum = num1 + num2;
        return sum;
    }

In the above example, the method name is "Sum" and the return type is int (returns an integer). It has two parameters num1 and num2, both of integer type. The code in the method body adds num1 and num2, stores the result in the sum variable, and returns the value of sum using the return statement.

Precautions:

1. Modifier: directly use public static fixed collocation at this stage
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
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, the method must be written in the class
7. In java, methods cannot be defined nested
8. In java, there is no method declaration

 

1.3 method call

To call a method, you need to write code in the following format:

返回值类型 变量名 = 方法名(参数列表);

Specific steps are as follows:

  1. Use the method's return type to declare a variable that will be used to store the method's return result. If the method has no return value (i.e. the return type is void), then there is no need to declare the variable.

  2. At the variable name on the left side of the equal sign, give the variable an appropriate name so that it can be referenced in subsequent codes.

  3. On the right side of the equal sign, write the name of the method to be called, and pass the parameters required by the method in parentheses. Make sure to pass the correct parameter type and number according to the method definition.

  4. After calling a method, the method will perform its defined operation and return a result (if there is a return value).

A simple code example is as follows: Find the sum of two numbers

// 定义一个名为Sum的方法,计算两个整数的和
public static int calculateSum(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}

// 在主程序中调用Sum方法
public static void main(String[] args) {
    int result = calculateSum(3, 5); // 调用calculateSum方法,并传入参数3和5
    System.out.println("Sum: " + result); // 打印结果:Sum: 8
}

The output code is as follows: 

In the above example, we defined a method called "calculateSum" that calculates the sum of two integers. In the main method of the main program, we call the calculateSum method and pass parameters 3 and 5. After the method is executed, the returned result 8 is assigned to the result variable and output to the console through the print statement. 

 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.

 

 1.4 The relationship between actual parameters and formal parameters

In the definition and invocation of a method, there are two types of parameters: formal parameters (formal parameters) and actual parameters (actual parameters).

  1. A formal parameter (formal parameter) is a parameter declared in a method definition that receives the value passed when the method is called. Formal parameters are equivalent to local variables inside the method and are only valid inside the method. Formal parameters specify their data types and names when the method is defined.
  2. Actual parameters (arguments) are concrete values ​​or variables that are passed to a method when the method is called. Actual parameters are passed in the order of the formal parameters in the method definition and must match the types of the formal parameters. Actual parameters can be constants, variables, or the value of an expression.
  3. When the method is called, the values ​​of the actual parameters are passed to the corresponding formal parameters. In this way, inside the method, the formal parameter can be manipulated with the actual parameter value passed in.

Let's understand with a real life example:

Suppose you have a factory that manufactures cars, and you have a car production line that produces cars. In this example:

- Formal parameters (formal parameters): automotive design drawings and specifications. Design drawings and specification sheets contain information such as the dimensions, accessory requirements, and assembly sequence of the car, which are equivalent to the parameters declared in the method definition. This information is not the actual car, but only used to describe the car to be produced.

- Actual Parameters (Actual Parameters): The car you actually produced according to the design drawings and specifications. These actual cars are processed and assembled by you according to the design drawings and specifications, which are equivalent to the specific values ​​or variables passed to the method when the method is called. According to design drawings and specifications, you use parts and assembly tools to process and assemble the car step by step, and finally get the actual car.

When you hand over your blueprints and specifications to your workers, they start building cars based on that information. They will use actual parts and tools to process and assemble according to the size and accessory requirements on the design drawings and in accordance with the prescribed assembly sequence. In this process, design drawings and specifications serve as formal parameters, while the actual production car serves as actual parameters. Workers process and assemble according to the actual design drawings and specifications, and finally produce the actual car.

As shown below:

 

Still cite the above example

// 定义一个名为Sum的方法,计算两个整数的和
public static int calculateSum(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}

// 在主程序中调用Sum方法
public static void main(String[] args) {
    int result = calculateSum(3, 5); // 调用calculateSum方法,并传入参数3和5
    System.out.println("Sum: " + result); // 打印结果:Sum: 8
}

 In the defined calculatesSum method, num1 and num2 are formal parameters, and the two numbers 3 and 5 stored in the main function main are actual parameters.


The value of the actual parameter is always copied to the formal parameter, and the formal parameter and the actual parameter are essentially two entities.

Explain with a piece of code  : swap two integers

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 exchange of the swap function, 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. why?
Because  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 , and the formal parameters x and y are two variables in the swap method, the values ​​of x and y The space is in the stack when the swap method is running, so: the actual parameters a and b and the formal parameters x and y are two unrelated variables. When the swap method is called, only the values ​​​​in the actual parameters a and b are copied A copy is 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.

 


1.5 Methods with no return value

A method without a return value means that in the method definition, the return type of the method declaration is `void`, which means that the method does not return any value.

public void printMessage(String message) {
    System.out.println(message);
}

In the above example, `printMessage` is a method that returns no value. It takes a string parameter "message" and prints that string to the console.

When a method with no return value is called, the corresponding operation is performed inside the method, but no value is returned to the caller. In the above example, when the `printMessage` method is called and passed a string argument, the method will print the string, but will not return any results.

Methods that do not return a value are typically used to perform some action or complete a specific task without returning a result. For example, printing information, updating data, sending notifications, etc. Such a method acts as a "side effect" on the execution of the program, that is, modifies the program state or performs a specific operation, but does not produce a return value that can be used for subsequent calculations.

When calling a method that does not return a value, you usually only care about the effect of the method execution, and do not need to receive the return result of the method.

Notice:

  1. The name of the formal parameter can be chosen arbitrarily, and has no effect on the method
  2. A formal parameter is just a variable that a method needs to use when it is defined, and is used to save the value passed when the method is called .
  3. In Java , the value of the actual parameter is always copied to the formal parameter, and the formal parameter and the actual parameter are essentially two entities

 

1.6 Significance of the method 

1. Modularization and code reuse: A method encapsulates a series of related operations together to form an independent module. This helps improve code readability, maintainability, and reusability.

2. Abstraction and encapsulation: methods allow developers to hide the logic and implementation details of the program inside the method, and only expose the necessary interfaces and functions to external callers.

3. Improve the maintainability and readability of the code: By using methods, the code is decomposed into multiple small, independent functional blocks, making the code easier to understand and maintain.

4. Improve the flexibility and scalability of the code: the method can accept parameters and return the result, so that the code can produce different outputs according to different inputs.

5. Implement object-oriented features: Methods are one of the basic building blocks of object-oriented programming. Through methods, object-oriented features such as encapsulation, inheritance, and polymorphism can be realized.

In conclusion, methods play an important role in object-oriented programming. They help us organize code into modular, maintainable, and reusable units, improving code readability, scalability, and maintainability. Methods are also the basis for implementing object-oriented features, allowing us to take better advantage of object-oriented programming.


 

2. Method overloading

2.1 Implementation of method overloading

 Method overloading refers to defining multiple methods in the same class with the same name but different parameter lists. Through method overloading, corresponding methods can be called according to different parameter types and quantities, so as to realize multiple methods with similar functions.

The example code is as follows:

public class Calculator {
    public static int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public int add(int a, int b, int c) {
        return a + b + c;
    }
}

In the above code,  Calculatorthe class defines three addmethods named , which have the same name but different parameter lists. The first addmethod takes two integers as arguments and returns their sum. The second addmethod takes two double-precision floating-point numbers as parameters and returns their sum. The third addmethod takes three integers as parameters and returns their sum.

Through method overloading, we can choose the appropriate method to perform the addition operation according to our needs. For example:

Calculator calculator = new Calculator();
int result1 = calculator.add(2, 3);                  // 调用第一个add方法,返回5
double result2 = calculator.add(2.5, 3.5);           // 调用第二个add方法,返回6.0
int result3 = calculator.add(2, 3, 4);               // 调用第三个add方法,返回9

By passing different parameter types and quantities, we can correctly call the appropriate method, realizing the flexibility of adding operations based on different parameters.

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)
3. It has nothing to do with whether the return value type is the same
// 注意:两个方法如果仅仅只是因为返回值类型不同,是不能构成重载的
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 个错误


 

2.2 Significance of method overloading

  1. Improve code readability and maintainability

  2. Optimize code structure and design

  3. Easy to call and use

  4. Improve code compatibility

In short: Method overloading is of great significance in object-oriented programming. It provides a more flexible, more readable, and better maintainable code writing method, making code design and calling more convenient and easy to understand.


2.3 Method signature

We know that in Java, two identifiers with the same name cannot be defined in the same scope. For example: two variables with the same name cannot be defined in a method, so why can a method with the same method name be defined in a class ?

This involves the method signature: the final name of the method after the compiler compiles and modifies it.

Specific method: method full path name + parameter list + return value type to form the complete name of the method.

For example the following code:

public class TestMethod {
    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) {
           add(1,2);
           add(1.5, 2.5);
   }
}

After the above code is compiled, then use the javap disassembly tool that comes with the JDK to view it. The specific operations are as follows:

1. First compile the project to generate a .class bytecode file
2. Enter the directory where the .class to be viewed is located in the console
3. Input: javap -v bytecode file name 

 

Description of some special symbols in the method signature:

 


 

Well, this is the end here, if there is anything wrong, please point it out in the comment area, thank you.

It is not easy to create, if possible, please support me three times. Knotabagi Yuhito would agree.

 

 

Guess you like

Origin blog.csdn.net/LHY537200/article/details/132229070