Java value delivery mechanism

Shaped involved in argument

Parameters need to pass out of the method is invoked: shape parameter

Arguments: method is invoked when the incoming actual values

Parameter passing mechanism in Java is only one method: the value passed

  • Parameter is the basic data type, then the basic data types stored "data value" parameter passed

  • Reference parameter data type, the data type of the variable will be referenced "address value" to the parameter

Basic data types

  1. main push method, m and n initialization values ​​are 10 and 20,

  2. swap push method, the values ​​of m and n incoming process parameter swap in and swap value in the method, the exchange of m and n, the outputswap方法里,m的值为10,n的值为10

  3. swap the method ends, popped, only the member variables inside the main method, the output交换结束后,变量m的值为20,n的值为10

Reference data types

  1. First, push the main method, performed at Data d = new Data()the time, the JVM creates a Data () and opens up an instance of the object instance in the memory to store heap space, while the address value (assuming the address value 0x0011) assigned to the variable d, since the Data Class m and n are not to be initialized, the default value of type int 0

  2. d.m=20And d.n=20modified so that the original value of m = 10, n = 20

  3. swap push method, parameter data values are the main method swap(d)of this assignment statement is over, the address values, is 0x0011, it is also pointed that instance

  4. swap method further defines a local variable tmp, as long as it is a local variable on the stack space, so the space on the stack tmp, assign it the value of m and, tmp = 10. Then the value of m and n exchange, exportswap方法里,m的值为20,n的值为10

  5. swap method ends after the end of it popped

  6. Execute the main method in the output statement, the main method or point to that instance, output交换结束后,变量m的值为20,n的值为10

The static keyword

After reading you may find that the basic data types main method has TransferTest1 t = new TransferTest1()the time, and call swap method t.swap(m,n);

And reference block data type main method used directly swap(d), because the definition of the swap method statickeyword

The basic role of the static keyword is a word to describe:

Convenient call (method / variable) in the case did not create the object down.

很显然,被static关键字修饰的方法或者变量不需要依赖于对象来进行访问,只要类被加载了,就可以通过类名去进行访问。

所以第一块代码也可以写成


public class TransferTest1 {
  public static void main(String[] args) {
    int m = 10;
    int n = 20;
    swap(m, n);
    System.out.println("交换结束后,变量m的值为" + m + "n的值为" + n);
    }
  public static void swap(int m, int n) {
    int tmp = m;
    m = n;
    n = tmp;
    System.out.println("swap方法里,m的值为" + m + "n的值为" + n);
  }
}

Guess you like

Origin www.cnblogs.com/codecheng99/p/12439831.html