function
Brief
Function is a specific function completion code block
Definition Format:
Modifier return type method name (parameter type parameter name 1, parameter type parameter name 2 ...) {
Method body;
return Return value;
}
public static int sum(int x, int y){ return x + y; }
Description:
A: Remember the current public static modifiers
B: Return Value Type used to define the data type of the return value
C: a method name names, for convenience we call the method
D: parameter type is received for the call type of the incoming process data
E: when receiving incoming calls methods for parameter name of the variable data
F: The method completion code body functions
G: return the end of the method, the return value gives the caller
Two distinct methods:
A: The return value type of data types explicitly Results
B: There are several parameters define the parameter list, and the type of the parameter
note:
For a function call that returns a value which is preferably assigned to a variable, to facilitate subsequent operation.
Method overloading
In the same class, there is a method to allow more than one of the same name, as long as they have different number of parameters or parameter types can.
Feature
Regardless of the return type, just look at the method name and parameter list
public class Student { public void test1(){ //do something } public void test1(int x){ //do something } public int test1(float x){ return 0; } }
note:
When called, the virtual machine to distinguish between the different methods of the same name parameter list.
Parameter passing
Parameter function is a primitive type, parameter change does not affect the argument,
Function parameter is a reference type, the effect of varying parameter argument.
public class Student { public static void change(int x, int[] arr){ System.out.println("change begin: " + x + "," + Arrays.toString(arr)); //1, [1, 2, 3] x += 1; for (int i = 0; i < arr.length; i++){ arr[i] += 1; } System.out.println("change end: " + x + "," + Arrays.toString(arr)); //2, [2, 3, 4] } public static void main(String[] args) { int a = 1; int[] array = {1, 2, 3}; System.out.println("main begin: " + a + "," + Arrays.toString(array)); //1, [1, 2, 3] change(a, array); System.out.println("main end: " + a + "," + Arrays.toString(array)); //1, [2, 3, 4] } }
Reference: "dark horse JAVA foundation"
Reference: "JAVA core technology"