Java Study Notes 4 (method) and java Study Notes 4
Methods are similar to functions in c ++. The difference is that java's method definition is not limited. The definition in c ++ must be declared before the function call after the main function:
Example of the rectangular area method:
Public class MethodDemo {public static void main (String [] args) {int area = getArea (5, 6); System. out. println ("area:" + area);} public static int getArea (int w, int h) {return w * h ;}}
Output: Area: 30
Call Process Analysis:
1. Enter from main and start executing the program
2. Call the getArea method and pass the parameter to obtain the returned value.
3. Output
Memory Analysis of call process:
1. During the program running period, you must enter the memory. Run file: The compiled class file enters the memory.
2. Enter the method area for the class file
3. Run the main method in the stack.
4. Run the getArea method on the stack.
5. The calculation result is returned to the caller.
6. The getArea method stops running, the stack is released, and memory resources are released.
7. After the main output, the stack is released, memory resources are released, and the program ends.
Note:
1. The method cannot be defined in another method.
2. method names are case sensitive
3. parameters cannot be transmitted less or more, with the same type
4. return indicates the end. It cannot be written under return. The return type is the same.
Method overload:
The specific concept of overload is not introduced. Here we implement the simplest overload
public class MethodDemo{ public static void main(String[] args){ int sum = getSum(2,3,1); System.out.println(sum); } public static int getSum(int a, int b){ System.out.println("int+int"); return a+b; } public static int getSum(int a, int b, int c){ System.out.println("int+int+int"); return a+b+c; } public static double getSum(double a, double b){ System.out.println("double+double"); return a+b; }}
Another difficulty:
public class MethodDemo{ public static void main(String[] args){ int[] arr = {1,2,3,4}; System.out.println(arr[2]);//3 change(arr); System.out.println(arr[2]);//100 } public static void change(int[] arr){ arr[2] = 100; }}
Explanation:
1. Run the main method in the stack.
2. Add the array ARR in the heap and assign a value to it.
3. The first address of the array is transmitted to the ARR in the stack, that is, the ARR points to the memory space containing the array.
4. The parameter method passed by calling change is actually the memory address. The address of the ARR variable in change is the same as the address of the ARR variable in main.
5. The memory is released after the change method is run, but the arr [2] changed by address completely.
In plain terms: when multiple people share a house, they all get the address of the house. When a person enters the house renovation, all the people entering the house will see the house after the renovation.