Java中经常把值传递和引用传递混淆,其实一般来说,值传递只相对于基本数据类型和
String数据类型,其余的一般都是引用传递。
先举值传递的例子:
package JavaStaticOrNotFunction; public class ChangeSimpleType { public static void main(String[] args) { //基本类型作为参数的时候,传递的是值 //String作为参数的时候,传递的也是值 int i = 70; String j = "hello"; change(i); change(j); System.out.println(i); System.out.println(j); } public static void change(int i) { i = 90; } public static void change(String j) { j = "world"; } }
下面是引用传递的例子:
package JavaStaticOrNotFunction; public class ChangeTest { public static void main(String[] args) { StringBuffer b = new StringBuffer("hello"); StringBuffer b2 = new StringBuffer("hello"); change(b); change2(b2); System.out.println(b); System.out.println(b2); } public static void change(StringBuffer s) { s.append("world"); } public static void change2(StringBuffer s) { s = new StringBuffer("world"); } }
Java杂谈之值传递和引用传递,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010792238/article/details/38439441