Java语言中参数传递是常见的问题之一,通过阅读如下测试代码,可以看看你是否真的了解java常见的参数传递的规则。
Java代码:
public class TestChangeParamInt { public static void main(String[] args) { int n = 3; System.out.println("Before change : " + n); changeData(n); System.out.println("After changeData(n) : " + n); } public static void changeData(int n) { n = 10; } } public class TestChangeParamObj1 { public static void changeData(StringBuffer strBuffer) { strBuffer.append("World!"); } public static void main(String[] args) { StringBuffer strBuffer = new StringBuffer("Hello "); System.out.println("Before change : " + strBuffer); changeData(strBuffer); System.out.println("After changeData(n) : " + strBuffer); } } public class TestChangeParamObj2 { public static void main(String[] args) { StringBuffer strBuffer = new StringBuffer("main "); System.out.println("Before change = " + strBuffer); changeData(strBuffer); System.out.println("After changeData(n) = " + strBuffer); } public static void changeData(StringBuffer strBuffer) { strBuffer = new StringBuffer("Change "); strBuffer.append("World!"); } } public class TestChangeParamObj3 { public static void main(String[] args) { StringBuffer strBuffer = new StringBuffer("Hello "); System.out.println("Before change = " + strBuffer); changeData(strBuffer); System.out.println("After changeData(n) = " + strBuffer); } public static void changeData(StringBuffer strBuffer) { StringBuffer sb2 = new StringBuffer("change "); strBuffer = sb2; sb2.append("World!"); System.out.println("In changeData(n) = " + sb2); } }