编程知识 cdmana.com

The method of Java programming foundation

The outline

Method introduction

summary

The cycle operation described before , What can be solved is code duplication , But the repeated code at this time must be regular . The loop operation , Can you solve all code duplication ? The answer must be No , For example, repeat operation for a certain function , The loop can't be implemented , We can use the method .

A game of War I was written , The program is running , You need to keep firing bullets . Suppose the function of firing bullets needs to be written 200 Line code , that , Every time you fire a bullet, you have to write this over and over again 200 Line code , Such a program is too low 了 . In development, we should follow DRY principle (Don’t Repeat Youself)—— Don't repeat your own code , Because repetition means maintenance costs are high , If you want to modify the function code , Every repetition should be revised once , Do you dare to make sure that every repetition can be changed to ? Don't you get bored ?

In order to solve the problem of repeated functional code , You can extract the code for firing bullets and put it in a code block ( a pair {}) in , And give this code a unique name , such , Each time you launch a bullet, you can call the function code of the bullet by this name . This block of code we call a method .

The way is <font color="red"> A collection of operations that are encapsulated together , Used to perform a function operation . </font>

advantage

  • Make the program shorter and clearer .
  • It's good for program maintenance .
  • Can improve the efficiency of program development .
  • Improved code reuse .

Definition and use

Declaration format :

[ Modifier ]  Method return value type   Method name ( Parameter list ) { 
     Method body ;
    return  Return value ; 
} 
// There are methods of return value type 
public static int add(int a, int b, int c ){  // Sum up 
    int k = a + b + c; 
    return k; 
}
// There is no way to return a value , No formal parameters 
public static void printStar(){ // Print 5 That's ok 5 The stars of the column 
    for(int i=1;i<=5;i++){
        for(int j=1;j<=5;j++){
            System.out.print("* ");
        }
        System.out.println();
    }
}
  • Access modifier : The permission range allowed to be accessed by method ;
  • return type : If the method does not return any value , Is specified as void; If the method has a return value , You need to specify the type of return value , And use... In the method body return Statement return value ;
  • Method name : Define the name of the method , You must use a legal identifier , See the name and know the meaning .
  • Parameter list : Parameters can have multiple , Multiple parameters are separated by commas , Each parameter consists of parameter type and parameter name , Space off .

call :

When the method definition is complete , If you want to use , It has to be called . In the call , Control of the call is transferred from the method call to the method , Method encountered return perhaps } At the end , Return the call right to the call . That is to say ” Where to come from ” The routine .

 Method name ([ Argument list ])

Be careful :

  • Method does not call, does not execute
  • There are return values , Receive variables or receive anonymously ( Output or call )
  • Define methods, specify formal parameters , Call the method to specify the argument
  • Method call requires the same number of parameter arguments , Type match

The method goes deep

void keyword

One void Method , It doesn't return any value .

public static void print() {
    for(int i=1;i<=9;i++) {
        for(int j=1;j<=i;j++) {
            System.out.print(j+"*"+i+"="+i*j+"\t");
        }
        System.out.println();// Line break 
    }
}

A method with a return value type , Return value must be brought out .

public static int getSum(int a,int b){
    return a+b;
}

return keyword

return by Jump out of the way or Return value .

<font color="red"> Be careful : In a scope return After that, there is no more code </font>

public static int getSum(int a,int b){
    return a+b;
    System.out.println("return There can be no code after !!!"); // Unreachable statements 
}

return sentence :

  1. return Statements can appear in any ( There are return values and no return values ) In the method
  2. return sentence In a method that does not return a value , Used to end the method ahead of time

    // Print out 1~5 Between the first two numbers 
    public static void test(){
        for(int i=1;i<=5;i++){
            if(i==3){
                return; // The ending method 
            }
            System.out.println(i);
        }
    }
  3. return sentence In methods with return values , It does two things : Early end method , Send out the results .

    // Find out 1~100 Before 5 One can be 2 The sum of divisible numbers 
    public static int getSum(int a,int b){
        int sum=0; // and 
        for(int i=1;i<=100;i++){
            sum+=i;
            if(i==5){
                return sum; //1) Early end method  2)  Bring out the return value 
            }
        }
    }
  4. Only one method can execute return sentence
  5. It's bound to be executed return After the statement , The statement written is unreachable , The program automatically detects this statement , It will never be carried out to , Report errors .
  6. Unconditional in a cycle break Write a statement after , There will be unreachable statements
  7. In the dead cycle ( No, break To end the cycle ) Write a statement after , There will be unreachable statements

Think about it

​ When writing a method , Please think about these four aspects :

1)、 Determine the function of the method

2)、 Determine the name of the method

3)、 Whether this method can run independently , Can't be independent , It needs external data to participate in the calculation , Determine the parameters .

4)、 After this method is completed , Whether the result directly affects the subsequent operation at the call , If it affects , Determine the return type , No effect is void

Signature (signature)

Method signature , Ensure uniqueness in a class . The signature of the method only looks at Method name and parameter

( type Number And order ) , With the modifier Return type It has nothing to do with parameter names .

public static void getSum(int x,int y){} -->getSum(int x,int y) Sign the method 

Type compatible

When a method is called , Formal parameter and actual parameter , Receive type should be compatible with return type and return value type .

① Shape parameter >= Actual parameters

public static void main(String[] args) {
   // int i=5;
    byte i=5;
    int x=test(i); //i Actual parameters 
}
public static int test(int d){ //d Shape parameter 
    return 'a';
}

② Type of reception >= return type >=return type

public static void main(String[] args) {
    int x=test(5);  //x Is the type of variable that receives the return value 
}
//int Is the return value type of the method ( Regulations return The value of the latter data can only be <=int)
public static int test(int d){ //d Shape parameter 
    return 'a'; //return The type of data that follows 
}

Value passing and reference passing

Value passing and reference passing :
So called value transfer , That is, only the value of the object is passed to the target object , Equivalent to copy; The system will re open up an identical memory space for the target object .

public static void main(String[] args) {
    byte i=5;
    test(i); // amount to test(5) --> Value passed 
    System.out.println(i);  //5
}
public static void test(int i){ 
    i++; // local variable i++;
}

The so-called quotation , In other words, the address of the object in memory is passed to the target object , It is equivalent to making the target object and the original object correspond to the same memory storage space . here , If you modify the target object , The data in memory will also change .

public static void main(String[] args) {
    Person p = new Person(" Zhang San ",18);
    test(p); //i Actual parameters 
    System.out.println(p.age); // reference |p The address value pointing to the object 
}
public static void test(Person p){ 
    p.age++;
}

Memory division :

JVM Memory division :

The characteristics of the stack :

Station describes the memory model of method execution , Every method is called A stack frame will be created ()

During the program run time , Method memory analysis :

public class MethodTest {
    public static void main(String[] args) {
        int w=5;
        int h=7;
        int area=getArea(w,h);
        System.out.println(area);
    }
    // Find the area 
    public static int getArea(int w,int h) {
        return w*h;
    }
}

The process 1:

1) Program to run , When executed java On command , Put class information MethodTest.class Load into memory

2) virtual machine JVM call main Method , The main method runs on the stack , In the stack for main Method to open the stack frame , Storage main Local variables in the

​ int w=5; int h=35;

3)main Call in method getArea() Method , In the stack getArea Method to open the stack frame

4) Method stack execution and assign values to formal parameters int w=5;int h=7; The result of calculation and return 35; Returns the result to the caller of the method

5) Method getArea completion of enforcement , Pop the stack to free memory

6) Carry on main The content of the method is , Local variables are stored in stack space int area = 35;getArea The return value of the method is assigned to area

7)main Method execution completed , Pop stack to free memory space

heavy load (Method OverLoad)

Generally speaking , The same method of function points is suitable for overload , Heavy load must meet the following requirements :

① Must be the same class

② Method name must be the same

③ Different parameter list

public class Demo {
 
    // A common method , With no arguments , No return value 
    public void add(){
        //method body
    }
    
    // Overload the method above , And with a shaping parameter , No return value 
    public void add(int a){
        //method body
    }
    
        // Overload the method above , And it takes two integer parameters , The return value is int type 
    public int add(int a,int b){
        //method body
        return 0;
    }

}

Be careful : Method overload has nothing to do with the return value .

Different parameter list :

​ The number of parameters is different .

​ The corresponding data types of parameters are different .

​ The order of the parameters is different ( Different types can exchange positions )

Recursive structure

Recursion is a common way to solve problems , That is to simplify the problem gradually . The basic idea of recursion is Call yourself ”, A recursive method will call itself directly or indirectly . Using recursion can solve some complex problems with simple programs . such as : Most sorts use recursive algorithms .

Recursive structure consists of two parts :

  1. Define recursive headers . answer : When not to call your own methods . If there is no head , Will fall into a dead cycle .
  2. Recursive body . answer : When do I need to call my own methods .
public static void print(int i) {
    System.out.println(i);
    if(i==10){ // Recursive header 
        return; // Early end method 
    }
    print(++i); // recursive 
}

public static void main(String[] args) {
    print(1);  // Print 1~10 Data between 
}
public static void recursion(int i) {
    System.out.println(" Holding ");
    if (i==0) { // critical condition 
        System.out.println(" My little carp ");
    } else {
        recursion(--i);  //  Recursively call 
    }
    System.out.println(" Of me ");
}

public static void main(String[] args) {
    System.out.println(" I was so scared that I picked up ");
    recursion(2);
}

The flaw of recursion :

Simple programs are one of the advantages of recursion . But recursive calls take up a lot of system stack , Memory consumption , When there are many levels of recursive calls, the speed is much slower than the loop . So be careful when you use it again .

Be careful : Any problem that can be solved recursively can also be solved iteratively . But recursive methods can reflect the problem more naturally , And easy to understand and debug , And when efficiency is not emphasized , You can use recursion ;

Avoid using recursion when high performance is required , Recursive calls take time and memory .

版权声明
本文为[Xu Yuxi]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224153720662B.html

Scroll to Top