method
The loop operation explained earlier can solve the problem of code duplication, but the repeated code at this time must be regular. Can loop operation solve all code duplication? The answer is definitely No. for example, the repeated operation for a certain function can not be solved in a cycle. Finally, the method should come on stage.
for instance:
Write an aircraft war game. During the operation of the program, you need to constantly fire bullets. Assuming that 200 lines of code are required for the bullet firing function, the 200 lines of code need to be written repeatedly every time the bullet is fired. Such a program is too low. In development, we should follow the DRY principle (Don't repeat yourself) - Don't repeat your own code, because repetition means great maintenance cost. If you want to modify the function code, you should modify every repeated place. Do you dare to ensure that every repeated place can be changed? Besides, aren't you bored? Isn't it boring?
In order to solve the problem of repeated writing of function code, the bullet firing code can be extracted and specially placed in a code block (a pair of {}), and a unique name can be given to this code. In this way, the bullet firing function code can be called directly through this name every time the bullet is fired.
In the above process, the extracted code can be a method defined in the class.
Definition of method
Method: code block definition method to complete a specific function (such as summation, counting quantity, etc.).
Syntax format:
[Modifier ] return type Method name (parameter type parameter name 1),Parameter type (parameter name 2){ Method body; [return Return value;] }
Look at the definition of the main method.
Format analysis:
(1) Modifiers: public, static, etc. static modified methods can be called directly using the class name. At present, static modification is used;
(2) Return type: defines the type of return value. After completing a function, the method:
If you need to return a result to the caller, write the type of returned data;
If you do not need to return the result to the caller, the keyword void is used to indicate that there is no return.
(3) Method name: it is used to call the method, follow the identifier specification, use verbs, the first letter is lowercase, and use hump representation;
(4) Formal parameter: the variable in parentheses of the method. There can be multiple variables;
(5) Method body: the code in {} of the method to write the code on how to complete the function;
(6)return keyword: use the return keyword in the method body.
Function 1: return the value to the method caller. At this time, the method cannot be modified with void;
Function 2: end the current method.
Note: when the method body has no return, the return type of the method is declared void, indicating no return.
(7) Actual parameter: the parameter value actually passed when a specific method is called.
be careful:
(1) Methods must be defined in classes. In Java, the smallest program unit is a class. There must be a class first. Multiple methods can be defined in a class;
(2) Methods and methods are parallel. You cannot define another method in a method. The definition of methods has no order.
Method call
(1) In the MethodDemo class, define a method to sum two integers
Method definition analysis:
Which two integers are the sum of two numbers? It indicates that there are two unknown factors, which are represented by two variables of type int. This method requires the sum of two numbers. It must return a result to the caller. Otherwise, it is meaningless.
static int getSum(int a,int b){ int c = a + b; return c; }
be careful:
(1) int a and int b in the method are formal parameters. Even if the parameter names are not a and B, it does not affect them, but the variable name is unique.
(2) Method is defined and must be called to take effect.
Method call
(1) Method call format: because the method is static modified, it can be called directly with the name of the class where the method is located.
(2) If the method has a return type, you need to define the variable of the return type, accept the result returned by the method and print it, which is meaningful.
(3) The place where the method is called can be called the caller
Syntax format: Return value type Variable = class name of the method. Method name (actual parameter);
(4) When calling a method, the passed parameters 2 and 3 are the actual parameters, which are referred to as parameters, and are related to order and type.
The complete code is as follows:
public class MethodDemo { static int getSum(int a,int b){ int c = a + b; return c; } public static void main(String[] args) { int result = MethodDemo.getSum(1, 2); System.out.println(result); } }
Drawing analysis:
Method design
(1) Defines a method to print a specified string with a specified number of lines
static void print(int line,String output){ for (int i = 0; i < line; i++) { System.out.println(output); } }
Call method:
public static void main(String[] args) { Demo40.print(7,"Hello"); }
(2) Define a method to pass in an int array and print the int type array according to the format
static void printArray(int[] arr){ String str = "["; for (int i = 0; i < arr.length; i++) { str = str + arr[i]; if (i == arr.length - 1) { str = str + "]"; }else { str = str + ","; } } System.out.println(str); }
Call method:
public static void main(String[] args) { int[] arr = new int[]{1,2,3,4,5}; Demo41.printArray(arr); }
(3) Defines a method that passes in an int array and returns the index of the first occurrence of the specified element in the array
static int indexOf(int[] arr,int key){ for (int i = 0; i < arr.length; i++) { if (arr[i] == key) { return i; } } return -1; }
Call method:
public static void main(String[] args) { int[] arr = new int[]{1,2,3,4,5}; System.out.println(Demo42.indexOf(arr, 3)); }
(4) Define a method to pass in an int array and return the average number of all elements of the array
static double getAvg(int[] arr){ int total = 0; for (int ele: arr){ total += ele; } return total / arr.length; }
Call method:
public static void main(String[] args) { int[] arr = new int[]{1,2,3,4,5}; System.out.println(Demo43.getAvg(arr)); }
(5) Define a method and pass in two parameters. A double array represents the price of multiple goods and a double discount returns the total price of goods
static double getTotalPrice(double[] arr,double cutOff){ double total = 0; for (double ele: arr){ total += ele; } return total * cutOff; }
Call method:
public static void main(String[] args) { double[] arr = new double[]{1,2,3,4,5}; System.out.println(Demo44.getTotalPrice(arr, 0.5)); }
Method variable parameters
There is a simpler way to pass an array in a method - the variable parameters of a method. Its essence is a syntax sugar. The purpose is to make it easier for developers to write code.
(1) The underlying variable parameter of the method is a one-dimensional array type
(2) The variable parameter must be the last parameter of the method to avoid the ambiguity of multiple parameters
(3) Corollary: a method has at most one variable parameter
(6) Define a method and pass in two parameters. A double array represents the price of multiple goods and a double discount returns the total price of goods (using variable parameters)
static double getTotalPrice(double cutOff,double... arr){ double total = 0; for (double ele: arr){ total += ele; } return total * cutOff; }
Call method:
public static void main(String[] args) { double[] arr = new double[]{1,2,3,4,5}; System.out.println(Demo45.getTotalPrice(0.8, arr)); System.out.println(Demo45.getTotalPrice(0.8, 1,5,9,7)); }
Method overloading
(1) Parameter list: parameter type + parameter number + parameter order
(2) Method signature: method name + method parameter list. In the same class, the method signature is unique. Otherwise, an error will be reported during compilation
Method Overload means that more than one method with the same name is allowed in the same class, as long as their parameter lists are different.
Method overload judgment principle: "two are the same and different"
Two same: in the same class, the method name is the same;
I. different: different method parameter lists (parameter type, number of parameters, and parameter order).
As long as the parameter type, the number of parameters and the order of parameters are different, it is called the parameter list. The function of different method overloads: methods that shield the same function have different method names due to different parameters.
Note: method overloading has nothing to do with the return value type of the method, but the return value type is generally required to be the same.
Value Passing Mechanism of method parameters
Basic type parameters
static void change(int x) { System.out.println("change before,x=" + x); //10 x = 100;// Modify the value of the x variable System.out.println("change after,x=" + x);//100 } public static void main(String[] args) { int a = 10; System.out.println("main before,a=" + a);//10 change(a); System.out.println("main after,a=" + a);//100? 10? }
Output results:
main before,a=10 change before,x=10 change after,x=100 main after,a=10
When the value of the a variable in the main method is copied and passed to the change method, the value of the a variable in the main method will not be changed.
Reference type parameter
static void change(int[] arr) { System.out.println("change before,arr[0]=" + arr[0]);//10 arr[0] = 30; //Modify the value of the first element in the array System.out.println("change after,x[0]=" + arr[0]);//30 } public static void main(String[] args) { int[] a = new int[] { 10, 90 }; System.out.println("main before,a[0]=" + a[0]);//10 change(a); System.out.println("main after,a[0]=" + a[0]);//30 }
Output results:
main before,a[0]=10 change before,arr[0]=10 change after,x[0]=30 main after,a[0]=30
That's all for the fifth day of getting started with Java.
Data document address: Zero basics of Java development: day05 method.pdf