Java passes parameters to methods, will the parameters be changed?

There is no so-called passing by value and passing by reference in the parameter passing of methods in Java. Passing by value and passing by reference are already history. In Java, there is only passing by value, and the parameter passing is a copy of the parameter. This copy is a value in the basic data type, and the object type is Quote!

Value type: Basic data type
Reference type: Types other than basic data types
1. Value transfer: Applicable to basic data types and immutable classes (String, the basic type wrapper type is a reference type, but follows the value transfer rules), transfer What is important is the copy of the data, and the change of the called object to the new data does not affect the value of the original data

2. Reference data type: What is passed is a copy of the reference address. The change of the called object to the new data affects the value of the original data, because although the references of the new data and the original data are different, they point to the same data object in the heap.

package com.wugeek.test;
/**
* @author 作者 :peanut.w
* @version 创建时间:2017年12月9日 下午4:13:17
* 类说明
*/
public class TestPass {
	int a=123;//基本数据类型int
	String b="123";//特殊的类string
	StringBuffer c=new StringBuffer("123");//引用数据类型
	public void method(){
		this.changeInt(a);
		System.out.println(a);
		this.changeString(b);
		System.out.println(b);
		this.changeStringBuffer(c);
		System.out.println(c);
		
	}
	public void changeInt(int x){
		x=1234;
	}
	public void changeString(String y){
		y="1235";
		
	}
	public void changeStringBuffer(StringBuffer stringBuffer){
		stringBuffer.append(456);
		
	}
	public static void main(String [] args){
		TestPass test =new TestPass();
		test.method();
	}
	//输出结果:123   123   123456

}

Guess you like

Origin blog.csdn.net/peanutwzk/article/details/78760035