Concept of method
Method, also known as function, is the definition of an independent function and the most basic functional unit in a class.
The purpose of encapsulating a function as a method is to realize code reuse and reduce the amount of code.
Principle of method
Application principle of method:
(1) Must be declared before use
Classes, variables, methods, etc. should be declared before use
(2) Do not call, do not execute, call and execute once. Call once to push a method stack into the stack.
Classification of member methods
Member methods fall into two categories:
- Instance method: a method belonging to an object, which is called by the object.
- Static method: also called class method. It belongs to the whole class, not an instance, and is called by the class name.
Defines the format of the instance method
1. Syntax format
Modifier return value type method name([Parameter list: parameter type 1 parameter name 1,Parameter type 2 parameter name, ...... ]){ Method body; [return Return value;] }
- Modifier: public (one is written temporarily, which will be added later)
- Return value type: the data type representing the result of the method operation. After the method is executed, the result is returned to the caller
- Basic data type
- Reference data type
- No return value type: void
- Method name: give a name to the method. See the name to know the meaning, which can accurately represent the function of the method
- Parameter list: data from other methods needs to be used inside the method, and the data needs to be transferred through parameter transfer. It can be basic data type, reference data type, or no parameters and nothing is written
- Method body: specific function code
- return: ends the method and returns the result of the method,
- If the return value type is not void, there must be a [return value;] statement in the method body, and the type of the return value result must be consistent or compatible with the declared return value type.
- If the return value type is void, return does not need to be followed by the return value, or even there may be no return statement.
- No other code can be written after the return statement, otherwise an error will be reported: Unreachable code
2. The position of method declaration must be outside the method in the class (methods cannot be declared in methods)
Correct example:
class{ Method 1(){ } Method 2(){ } }
Examples of errors:
class{ Method 1(){ Method 2(){ //error } } }
Instance method call
-
The location of method invocation: invoked in another method.
Correct example:
class{ Method 1(){ Call other methods; } }
-
Classification of method calls:
-
Called separately in the following format:
Object name.Method name(parameter);
-
Output or return call in the following format:
System.out.println(Object name.Method name(parameter));//Directly output the return value after the method call or return Object name.Method name(parameter);//Directly return the return value after the method call as the return value of the current method
-
Assignment call, in the following format:
Data type variable name = Object name.Method name(parameter);
-
If the instance method is invoked in another instance method of this class, you can omit the object name.
class Count { /* Defines how to calculate the sum of two integers The return value type is int Parameters: sum uncertain data and define int parameters. Parameters are also called formal parameters */ public int getSum(int a, int b) { return a + b; } /* Defines how to calculate the difference between two integers The return value type is int Parameter: for the difference of uncertain data, the int parameter is defined. The parameter is also called formal parameter */ public int getSubtract(int a, int b){ return getSum(a,-b);//Directly return the result of the getSum(a,-b) method call as the result of getSubtract(a,b) } } public class Method_Demo1 { public static void main(String[] args) { // create object Count c = new Count(); // Calling methods by individual calls c.getSum(3,4); // Call method by output call System.out.println(c.getSum(3,4)); // Calling methods by assignment int sum = c.getSum(3,4); System.out.println(sum); } }
- Formal parameter: when defining a method, the variable name in parentheses after the method name is called formal parameter (formal parameter for short), that is, the formal parameter appears in the method definition.
- Argument: when calling another method in the caller's method, the parentheses in the name of the method are called the actual parameters (referred to as the actual parameters), that is, the arguments appear in the caller's method.
Summary:
(1) When calling, you need to identify which method to call by method name
(2) When calling, you need to pass "arguments", and the number, type and order of arguments should correspond to the formal parameter list one by one
If a method has no formal parameters, it does not need and cannot pass arguments.
(3) When called, if the method has a return value, it can accept or process the result of the return value.
If the return value type of the method is void, you do not need and cannot receive and process the return value result.
Examples of defining and invoking instance methods
Declare customer, account and bank
- Declare Account class Account
- It includes two instance variables: account and balance
- Include save deposit method
- Including withdrawal method of withdraw
- Declare Customer class Customer
- Contains: name and mobile phone, ID number, an account owned, four instance variables
- Declare bank class BankClerk
- It contains the open method to open an Account for a Customer object and associate the information of Customer and Account objects
class Account{ String id; double balance; public void save(double money){ if(money > 0){ balance += money; }else{ System.out.println("Parameter error"); } } public void withdraw(double money){ if(money <0){ System.out.println("Parameter error"); }else if(money > balance){ System.out.println("Sorry, your credit is running low"); }else{ balance -= money; } } } class Customer{ String name; String tel; String cid; Account account; } class BankClerk{ public void open(Customer c, Account a){ c.account = a; } } public class Method_Exer6 { public static void main(String[] args) { //Create customer object Customer c = new Customer(); c.name = "Chai Linyan"; c.tel = "10086"; c.cid = "111111111111111111"; //Create a bank card account object Account a = new Account(); a.id = "12345678910"; a.balance = 0; //Bank object BankClerk b = new BankClerk(); b.open(c, a); System.out.println("full name:" + c.name + ",Telephone:" + c.tel + ",ID number:" + c.cid + ",account number:" + c.account.id + ",Balance:" + c.account.balance); //deposit c.account.save(1000); System.out.println("full name:" + c.name + ",Telephone:" + c.tel + ",ID number:" + c.cid + ",account number:" + c.account.id + ",Balance:" + c.account.balance); //withdraw money c.account.withdraw(2000); //display information System.out.println("full name:" + c.name + ",Telephone:" + c.tel + ",ID number:" + c.cid + ",account number:" + c.account.id + ",Balance:" + c.account.balance); } }
Method call memory analysis
The method does not call or execute, and the call is executed once at a time. Each call will have a stack entry action in the stack, that is, an independent memory area will be opened for the current method to store the value of the local variable of the current method. When the method execution is completed, the memory will be released, which is called out of the stack. If the method has a return value, the result will be returned to the calling function. If there is no return value, It ends directly, returns to the call and continues to execute the next instruction.
Stack structure: first in first out, last in first out.
class Test18_Invoke_Memory{ public static void main(String[] args){ Count c = new Count(); int x = 1; int y = 2; int sum = c.getSum(x,y); System.out.println(x + " + " + y + " = " + sum); } } class Count{ public int getSum(int a, int b){ return a + b; } }
Variable parameters
After JDK 1.5, if we define a method, the type of a formal parameter can be determined, but the number of formal parameters is uncertain, we can use variable parameters.
Format:
Modifier return value type method name([List of formal parameters in the non variable parameter section,]Parameter type... Formal parameter name){ Method body; }
requirement:
(1) A method can only have one variable parameter
(2) Variable argument must be the last parameter in the formal parameter list
(3) In fact, this writing is "equivalent to"
Modifier return value type method name([List of formal parameters in the non variable parameter section,]Parameter type[] Formal parameter name){ Method body; }
However, for the latter definition, the array must be passed when calling. The former is more flexible. It can not only pass the array, but also directly pass the elements of the array. In fact, the compiled class file encapsulates these elements into an array and passes them. These actions are automatically completed when compiling the. Class file.
Benefits:
It also represents an array, but when calling this method with variable parameters, you don't need to create an array (that's the simplicity). You can directly pass the elements in the array as actual parameters. In fact, the compiled class file encapsulates these elements into a data group for transmission. These actions are automatically completed when compiling the. Class file.
Code demonstration:
public class ChangeArgs { public static void main(String[] args) { // create object Count c = new Count(); int[] arr = { 1, 4, 62, 431, 2 }; int sum1 = c.getSum1(arr); System.out.println(sum1); int sum2 = c.getSum2(arr); System.out.println(sum2); int sum3 = c.getSum2(1, 4, 62, 431, 2); System.out.println(sum3); } } class Count { // Completes the summation of all elements of the array // Original writing public int getSum1(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // Variable parameter writing public int getSum2(int... arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } }
Example 1: find the maximum value
Define to find the maximum value of 1-n integers
public class ChangeArgs_Exer1 { public static void main(String[] args) { Count c = new Count(); System.out.println(c.max(1)); System.out.println(c.max(5,3,2,6)); } } class Count{ public int max(int num, int... others){ int max = num; for (int i = 0; i < others.length; i++) { if(max < others[i]){ max = num; } } return max; } }
Example 2: String splicing
Defines to splice n strings. If no string is passed in, an empty string is returned
public class ChangeArgs_Exer2 { public static void main(String[] args) { StringUtil su = new StringUtil(); System.out.println(su.concat()); System.out.println(su.concat("hello","world")); } } class StringUtil{ public String concat(String... args){ String str = ""; for (int i = 0; i < args.length; i++) { str += args[i]; } return str; } }
Method overloading
- Method overloading: more than one method with the same name is allowed in the same class, as long as their parameter lists are different, regardless of modifiers and return value types.
- Parameter list: different numbers of data types, different data types, and different order of data types.
- Overloaded method call: the JVM calls different methods through the parameter list of the method.
Method overload example: compare whether two data are equal
Compare whether the two data are equal. The parameter types are two byte types, two short types, two int types and two long types respectively, and are tested in the main method.
public class Method_Demo6 { public static void main(String[] args) { //establish Count c = new Count(); //Define variables of different data types byte a = 10; byte b = 20; short c = 10; short d = 20; int e = 10; int f = 10; long g = 10; long h = 20; // call System.out.println(c.compare(a, b)); System.out.println(c.compare(c, d)); System.out.println(c.compare(e, f)); System.out.println(c.compare(g, h)); } } class Count { // Two byte type public boolean compare(byte a, byte b) { System.out.println("byte"); return a == b; } // Two types of short public boolean compare(short a, short b) { System.out.println("short"); return a == b; } // Two int s public boolean compare(int a, int b) { System.out.println("int"); return a == b; } // Two long type public boolean compare(long a, long b) { System.out.println("long"); return a == b; } }
Parameter passing mechanism of method
- Formal parameter: when defining a method, the variable name in parentheses after the method name is called formal parameter (formal parameter for short), that is, the formal parameter appears in the method definition.
- Argument: when calling another method in the caller's method, the parentheses in the name of the method are called the actual parameters (referred to as the actual parameters), that is, the arguments appear in the caller's method.
- Parameter passing mechanism of method: assigning values to formal parameters by arguments
- When the formal parameter of the method is a basic data type, the change of the formal parameter value will not affect the actual parameter;
- When the formal parameter of the method refers to a data type, the change of the address value of the formal parameter will not affect the argument, but the change of the data in the address value of the formal parameter will affect the argument, for example, modifying the value of an array element or modifying the attribute value of an object.
- Note: special types such as String and Integer are excluded
Example code 1:
class Test{ public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static void main(String[] args){ int x = 1; int y = 2; swap(x,y);//After the call, the values of x and y remain unchanged } }
Trap instance 1:
/* Trap 1: in the method, if the formal parameter = new object, it has nothing to do with the argument */ class Test{ public static void change(MyData my){ my = new MyData();//The parameter points to a new object my.num *= 2; } public static void main(String[] args){ MyData m = new MyData(); m.num = 1; change(m);//After the call, the num attribute value of the m object is still 1 } } class MyData{ int num; }
Trap example 2:
public class Test { public static void main(String[] args) { StringUtil util = new StringUtil(); String str = "Shang Silicon Valley"; util.change(str); System.out.println(str); } } class StringUtil{ public void change(String str){ str += "Hello";//The String object is immutable. Once modified, a new object will be generated } }
Command line parameters
The arguments passed through the command line to the formal parameters of the main method are called command line parameters
public class TestCommandParam{ //Formal parameter: String[] args public static void main(String[] args){ System.out.println(args); System.out.println(args.length); for(int i=0; i<args.length; i++){ System.out.println("The first" + (i+1) + "The values of the two parameters are:" + args[i]); } } }
Run command:
java TestCommandParam
java TestCommandParam 1 2 3
java TestCommandParam hello atguigu
Recursive method
- Recursion: refers to the phenomenon of calling itself within the current method.
- Recursive classification:
- There are two kinds of recursion, direct recursion and indirect recursion.
- Direct recursion is called the method itself.
- Indirect recursion can use method A to call method B, method B to call method C, and method C to call method A.
- matters needing attention:
- Recursion must be conditionally limited to ensure that recursion can stop, otherwise stack memory overflow will occur.
- Although there are restrictions in recursion, the number of recursions cannot be too many. Otherwise, stack memory overflow will also occur.
Example 1: calculate the sum of all natural numbers between 1-100
public class RecursionMethod1{ public static void main(String[] args) { Count c = new Count(); int sum = c.sum(100); System.out.println("1-100 And:" + sum); } } class Count{ public int sum(int n){ if(n == 1){ return 1; }else{ return n + sum(n-1); } } }
Example 2: calculate the nth value of Fibonacci sequence
Law: a number is equal to the sum of the first two numbers,
f(0) =1,
f(1) = 1,
f(2) = f(0) + f(1) =2,
f(3) = f(1) + f(2) = 3,
f(4) = f(2) + f(3) = 5
...
f(n) = f(n-2) + f(n-1);
public class RecursionMethod3{ public static void main(String[] args) { Count c = new Count(); System.out.println("f(10): " + c.f(10)); System.out.println("f Total number of times the method was called:" + c.total); } } class Count{ int total = 0; public int f(int n){ total++; if(n <= 1){ return 1; }else{ return f(n-2) + f(n-1); } } }