[Learn java happily ~ write code happily] The concept use of the method of the first acquaintance

Welcome to this column [Learn java happily ~ write code happily], today I will share with you the concept and use of methods in java, and more in-depth knowledge about method overloading and so on. Explain in detail in the next blog. Although the content of this chapter is very simple, I will still talk about it in great detail.

1. Citation example:

As the college entrance examination is approaching, many students have problems that are under pressure and difficult to solve. They all choose to communicate with teachers. The following is their communication content:

A few days later, several classmates had the same problem. They told the teacher that they were under a lot of pressure and didn't know how to study. At this time, the teacher had to do the work that was repeated before. At this time, the teacher thought, maybe more people will ask the same question in the future, and maybe some students are embarrassed to ask, so the teacher wrote a post and posted it on the school forum:

Then send the link of the post to the group, saying: Students who have been stressed recently, look here, https://www.xxx.com, students can click the link to see the content of the post.

From the above cases we can find:

1. The teacher organizes the common problems of the students into posts, which reduces repetitive work, and then has time to solve more problems of the students.
2. Students can click on the link to enter the post to read, and the problem is solved.
3. Students can click on the link to read at random, instead of repeating things with the teacher over and over again.

The same is true in programming. The code of a certain function may be used frequently. If it is reimplemented in each position, it will:
1. Make the program cumbersome
2. The development efficiency is low, and a lot of repetitive work is done
3. It is not conducive to maintenance. When it needs to be changed, all the places where the code is used need to be modified
. 4. It is not conducive to reuse.
Therefore, in programming, we can also encapsulate frequently used code into "posts" (methods), when needed Just use the link (that is, the method name - the entry address of the method) to use it, avoiding the cumbersomeness over and over again.

2. The concept and use of the method:

2.1 What is a method

   A method is a piece of code, similar to a function in C. The significance of the existence of the method:

(1) It is able to organize the code modularly (when the code scale is complex).

(2) The code can be reused (a code can be used in multiple places).

(3) Make the whole project more readable, better understandable and simpler.

(4) Directly call the existing method development, without repeating the wheel.

For example, if you want to develop a calendar now, in the calendar, you often need to judge whether a year is a leap year, and you have the following code:

int year = 1900;
if((0 == year % 4 && 0 != year % 100) || 0 == year % 400){        System.out.println(year+"year is a leap year"); }else{        System .out.println(year+"year is not a leap year");


}

The above is just a code segment used to implement this function. How should the method be defined?

2.2 Method Definition

Method syntax format:

//method definition

Modifier return value type method name (parameter type variable 1, parameter type variable 2...) {

        Method body code;
        return return value; // if there is no return value, do not write

}        

Modifiers include public, static, private, protected, etc., and I will explain them to you after they have functions in the method.

Precautions:

(1) Method name : It is recommended to use the small camel case for the method name (and when the method name consists of multiple words, the first word is all lowercase, starting from the second word, the first letter is capitalized).

(2) Return value : The return value type of the method should be consistent with the actual type returned. If there is no return value, it must be written as void.

(3) Parameters : If the method has no parameters, nothing needs to be written in (), if there are parameters, the parameter type needs to be written, and multiple parameters are separated by commas.

(4) Method body : The statement to be executed inside the method.

(5) In java, methods must be written in classes .

(6) In java, methods cannot be defined nested .

(7) In java, the method does not declare this .

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 for adding two integers

public class Method{        

      //Method definition 
      public static int sum(int x,int y){
      return x+y;
   }
}

2.4 Execution process of method invocation

Call the method --> pass parameters --> find the method address --> find the executed method body --> end the method and return --> return to the calling method and continue to execute

Note: When defining a method, the method body is generally not executed, only when the method is called. A method can be called multiple times.

Code Demonstration: Calculate the value of 1! + 2! + 3! + 4! + 5!

public class Test {
    public static void main(String[] args) {
        int sum=0;
        for(int i=1;i<=5;i++) {
            sum += fac(i);    //方法fac()被多次调用
        }
        System.out.println(sum);
    }
    public static int fac(int x){
        int mul=1;
        for(int i=1;i<=x;i++){
            mul*=i;
        }
        return mul;
    }

}

2.5 The relationship between actual parameters and formal parameters

A formal parameter is just a variable that the method needs to use when it is defined to accept the value passed when the method is called. Formal parameters are allocated space only when the method is called. In primitive types, a formal parameter is a temporary copy of an actual parameter, which is essentially two separate entities. The names of the formal parameters can be chosen arbitrarily and have no effect on the method.

for example:

public static void main(String[] args) { 
    int ret=add(2,3);//2,3 are actual parameters. When the method is called, x is used to save 2 and 3 
    System.out.println (ret); 
} 
public static int add(int x,int y){ //x,y are formal parameters, used to save the 2,3 passed when calling this method 
    return x+y; 
}

//operation result

5

Let's look at another example: swapping two integer variables

public class Test{
    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);
    }
} 

operation result: 

swap: x = 20 y = 10
main: a = 10 b = 2

From this we can find that the values ​​of x and y have been swapped, but the values ​​of a and b have not been swapped, it is still the same as before. Why is this?

Reason: As mentioned above, for the underlying type, the formal parameter is just a temporary copy of the actual parameter, that is, call by value. They are two independent entities, and a single operation on the formal parameters cannot change the formal parameters. It's as if you copied a paper written by your friend (here, 2 and 3 are equivalent to your friend's paper, and x, y are equivalent to the paper you copied from the past.), and then to yourself The copied paper was published with a series of revisions. In the end, it is conceivable that the last paper you published is not the same as your friend's paper, because the paper in your hand is only obtained by copying your friend's paper. Obviously, changing the copied paper will not affect you. The paper in the hands of a friend.

[Solution]: Pass reference type parameters (such as arrays to solve this problem)

The running process of this code will be explained in detail later when we learn about arrays.

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;          } }










// run result
arr[0] = 20 arr[1] = 10

2.6 Methods with no return value

The return value of the method is optional, and no return value is allowed, but the return value type must write void.

E.g:

public 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);         }

}

//operation result

x=10 y=20

The above is what I want to share today. I will continue to update it in the future. I will learn a lot by reading my blog often. 

Guess you like

Origin blog.csdn.net/m0_63039919/article/details/123439382