Chapter 5 methods and arrays
5.1. Method
5.1.1 method overview
01 concept
π Method: a code segment with a specific function. This code function is often used. Wrap it in curly braces and give it a name. Then take this name to represent this code.
For example: Scanner Class nextInt() method, nextInt For the method name, enter an integer through the keyboard each time, and call nextInt Method. without nextInt Method encapsulation. Each time the keyboard enters data, the logic needs to be re implemented
02 method advantages
(1) Improve code reusability (reuse)
(2) Improve the encapsulation of the code. The contents encapsulated by braces are invisible and inaccessible to other callers.
5.1.2 definition of method
01 method definition format
1. General method/Common method/Non static method Modifier return value type method name (parameter list) { Method body language sentence; return sentence; } 2. Static method Modifier static Return value type method name (parameter list) { Method body language sentence; return sentence; }
Definition and interpretation:
π (1) Modifier: Currently, all are written as public static
π (2) Return value type: the data type representing the result of method operation. When the method is completed, there may be output, and the output needs to be returned to the method caller. If you do not need to return results, use the keyword void to indicate that the method does not have any return value type.
π (3) Method name: get the name, legal identifier and small hump rule for the code.
π€£ (4) Parameter list: this code may need some resources to complete this function. Some variables will be defined in the parameter list. When this method is called in memory, data will be transferred from the outside and stored in these variable containers.
π (5) Method body sentence: the execution logic that really needs to complete the function of the method.
π (6)return statement: to return the final result to the caller, use the return statement. If there is no production result, you can not write return or write return; Used to indicate the end of a method.
02 method definition exercise
//Common method public void run() { System.out.print("run......") } //Static method public static void sleep() { System.out.print("sleep......") }
Case 1: define a static method function to sum any two integers
public class Demo01 { public static void main(String[] args) { System.out.println(sum(3,6)); } //A static method for finding the sum of two numbers public static int sum(int a,int b) { int sum = a + b; return sum; } }
π The main function calls the static method, which can be called directly through parameters.
Case 2 defines a method function to compare whether the data of two floating-point types are equal
1. General method
public class Demo01 { public static void main(String[] args) { //Call normal method Demo01 c = new Demo01(); boolean e = c.auu(3.23,5.6); if(e == true) { System.out.print("equal"); }else{ System.out.print("Unequal"); } } public boolean auu(double a,double b) { return a == b?true:false; } }
2. Static method
public class Demo01 { public static void main(String[] args) { //Call static method boolean e = auu(3.23,5.6); if(e == true) { System.out.print("equal"); }else{ System.out.print("Unequal"); } } public static boolean auu(double a,double b) { return a == b?true:false; } }
Case 3: define a method function to print 1-n integers (1-N any integer print, n is a positive integer)
public class Demo01 { public static void main(String[] args) { //Static method direct call print(6); } public static void print(int n) { for(int i = 1;i <= n;i ++) { System.out.println(i); } } }
Context: Configuration
π€ Static things are difficult to recycle and occupy memory. Try to use them less
π It is best to print in the main function. Ordinary methods only encapsulate logic
5.1.3 method call
01 method call format
Format: method name (actual parameter); Method name: the name of the method to be called, such as getsum. Actual parameters: actual parameters to be passed during method call, such as getsum(3,6);
02 three forms of method calls
Form name | Examples | matters needing attention |
---|---|---|
Direct call | getSum(3,6); | Commonly used for methods that do not return value results |
Print call | System.out.println(getSum(3,6)); | Used for methods that have return value results and need to be printed |
Assignment call | int sum = getSum(3,6); | Used for methods that have returned to and need to retain the returned value results |
03 πͺ Differences between ordinary method and static method call:
Non static method call: first new A new class, open up a new space, and then call the methods of the new class. Static method call: just call the method directly.
5.1.4 shape participation arguments
π« Formal parameter: the formal parameter is only used to receive the passed value, which is equivalent to giving a name to the passed value. It can be used at will. The actual data type is based on the actual parameter data type, and the name is optional. Receive in sequence
π** Actual parameter: * * the actual parameter has the transfer of specific actual values (what type is the first one when transferring parameters, and the following ones also default to this type)
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-5rxyrlcc-1638089591876) (C: \ users \ Lenovo \ appdata \ roaming \ typora user images \ image-20211121164641065. PNG)]
5.1.5 precautions for definition method
01 method definition considerations
(1) Methods cannot be nested and defined. Each method is independent.
//The following error example public static void print(int n) { for(int i = 1;i <= n;i ++) { System.out.println(i); } //Nested another method public static void sum(int m,int n) { return sum = m +n; } }
(2) There is no difference in the order of methods. They are at the same level.
(3) Methods can be nested or even called themselves
Test2 t = new Test2()
02 precautions for parameter list
1.Formal parameters: When defining methods, you need to add data type parameters, that is, variables are declared, and each variable is separated by commas. 2.Actual parameters: used in method call without adding data type parameters, that is, the assignment operation is performed on variables, and each variable is separated by commas. The order must be consistent with the order of the formal parameters in the defined method.
03 precautions for return statement
1.return The statement represents the end of the method,It also represents the output content of the method. 2.If the method has no specific return content,Can be written as return; At this time return Statements can be omitted,The return value class is void. 3.If the method has a specific return content,that return Then you need to add the return specific data,The return value type must be the same as the return value type of the defined method. 4.Who calls the current method,return Statement returns the data results obtained by the execution of the current method to who.as main Method call, it is returned to main method.
(4) A null pointer must appear in the reference data type
(5) The unopened space is null
5.1.6 method memory: method area
π€ Before jdk1.8, there was a name called persistent band / permanent generation, which many students should have heard. After jdk1.8, oracle officially changed its name to meta space, which is the method area. Store constant, static variable and class meta information.
π€ Stack memory: the method in the code needs to open up space in stack memory to run; When a method is called, it enters the stack memory (method pressing the stack) to open up space. After the method runs, it leaves the stack memory and releases the occupied space (method bouncing the stack dies)
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG swgxdlbi-1638089591878) (C: \ users \ Lenovo \ appdata \ roaming \ typora user images \ image-20211120151737967. PNG)]
5.1.7 method practice
Case 1 old man Wang buys wine:
(Money means parameters, Indicates the return value result) 1)Old man Wang went to buy wine for the first time,I found no money at the store,Then I didn't buy the wine back.output:No money to buy a hammer.(No parameter, no return value) 2)Old man Wang went to buy wine for the second time,I found no money at the store,But the landlady is an acquaintance,A communication,Brought back a bottle.(No parameter, return value) Erguotou. 3)Old man Wang went to buy wine for the third time,Just got paid,Go to the store,After giving the money,The boss is open to money,Take the money and run away,Only the old man(There are parameters but no return value) One person is messy. 4)Old man Wang went to buy wine for the fourth time,After giving money to the store,The boss gave old man Wang a bottle of jiangxiaobai.(There are parameters and return values)
Procedure:
public class Demo01 { public static void main(String[] args) { maiJiu1(); maiJiu2(); maiJiu3(1); maiJiu4(1); } public static void maiJiu1() { System.out.println("No money to buy a hammer"); } public static int maiJiu2() { System.out.println("Bring back a bottle of Erguotou"); return 0; } public static void maiJiu3(int a) { System.out.println("Messy in the wind"); } public static int maiJiu4(int a) { System.out.println("Bring back a bottle of jiangxiaobai"); return 0; } }
5.1.8 method overload
01 overload concept
π Method overloading: (Overload) multiple methods with the same method name and different parameter lists in the same class that are independent of the return value type are called overloads
πDifferent parameter forms: 1.Different parameter types 2.Different number of parameters 3.The order of parameter types is different;
02 advantages of heavy load
π€£ The method of the same functional logic only needs to remember one name. More convenient
π Improved code reusability
π Reduce memory usage
03 overload case
Case 1 three summations
Customer requirements define several methods: 1)It is required to sum two arbitrary integers 2)It is required to sum three integers 3)2 required double Floating point type summation scene: Three summation methods similar in function,Each method has its own method name,Not easy to remember,If you let something similar The function has the same method name, Distinguish multiple methods through different parameter lists,This can also be achieved,This is method overloading.
Procedure:
public class Demo01 { public static void main(String[] args) { System.out.println(sum(2,4)); System.out.println(sum(2,4,9)); System.out.println(sum(2.3,4.9)); } public static int sum(int a,int b) { return a + b; } public static int sum(int m,int n,int k) { return m + n + k; } public static double sum(double e,double l) { return e + l; } }
Case 2 three monks drink water
public class Demo01 { public static void main(String[] args) { System.out.println(water(1)); System.out.println(water(2,4)); System.out.println(water(2,3,4)); } public static int water(int one) { System.out.println("A monk carries water to eat"); return 0; } public static int water(int one,int two) { System.out.println("Two monks carry water to eat"); return 0; } public static int water(int one,int two,int three) { System.out.println("Too many cooks spoil the broth."); return 0; } }