In the actual development process, method invocation is a very common operation, in the method call, the processing of the parameters may be many of the actual development of the programmer does not necessarily understand very clearly, the following system describes the rules of the Java language parameters passing, as well as some of the problems related to parameter passing.
Similar to other programming languages, the Java language's parameter transfer can be divided into two types:
1. Pass by value
Scope of application: 8 Basic data types, string objects
Feature: Copy a piece of data in memory, transfer the copied data to the inside of the method
Function: Change the value of the parameter within the method, the external data will not follow the change
2, by Site delivery (by address)
Scope of application: array, all types of objects except string
Features: Passing the address of an object to the inside of a method
Function: Modify the contents of the object within the method, and the external data will change accordingly
Base Sample code:
public class Test1{
public static void t1(int n){
n = 10;
}
public static void t2(String s){
s = "123";
}
public static void t3(int[] array){
array[0] = 2;
}
public static void main(String[] args){
int m = 5;
t1(m);
System.out.println(m);
String s1 = "abc";
t2(s1);
System.out.println(s1);
int[] arr = {1,2,3,4};
t3(arr);
System.out.println(arr[0]);
}
}
According to the above parameters passing rules, the output of this code should be: 5ABC2. Because the int type is passed by value, when the parameter m is passed to the method T1, the equivalent of a copy of M's value is duplicated, and the value of the M is modified within the method T 1, so the value of M. is unchanged and the S1 output is similar to M. The arr is an array, which is transmitted by address, that is, the ARR addresses are passed to the method T3, and the original contents are changed when the values in the array are modified within the method T3.