java 值传递和引用传递详 解
最 近 遇到java 值传递和引用传递问题 ,做 了 一 个 小 小 的 测试,分享 一 下,先 看 代码: package com.test.pass;
public class TestPass {
/**
* @param args
*/
public static void main(String args) {
int p1 = 9;
int p2 = 10;
TestPass t = new TestPass();
t.add(p1, p2);
System.out.println("p1 = "+p1);
System.out.println("p2 = "+p2);
//pass by value
TestBO bo = new TestBO(10,20);
t.add(bo);
System.out.println("bo.m = "+bo.getM());
System.out.println("bo.n = "+bo.getN());
//pass by reference
int ps = new int;
ps = 1 ;
ps = 2 ;
t.add(ps);
System.out.println("ps0 = "+ps);
System.out.println("ps1 = "+ps);
//pass by reference
String sp = "Hello";
t.testStr(sp);
System.out.println("sp1 = "+sp);
t.testStr2(sp);
System.out.println("sp2 = "+sp);
//pass by value
}
public void add(int a,int b){
a = 2;
b = 3;
System.out.println("a = "+a);
System.out.println("b = "+b);
}
public void add(TestBO bo){
bo.setM(2);
bo.setN(3);
System.out.println("a = "+bo.getM());
System.out.println("b = "+bo.getN());
}
public void add(int as){
as = 10 ;
as = 20 ;
System.out.println("as = "+as);
System.out.println("as = "+as);
}
public void testStr(String str){
str = "world";//equals String str = new String("world");
System.out.println("str1 = "+str);
}
public void testStr2(String str){
System.out.println("str2 = "+str.concat(" World!"));
System.out.println("str22 = "+str);
}
}
class TestBO{
private int m;
private int n;
public TestBO(int m,int n){
this.m = m;
this.n = n;
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
}
总结: Java中进行方法调用的时候传递参数时,遵循值传递的原则: 1)基本数据类型(byte,short ,int ,long, float ,double,boolean,char),传递的是数据的拷贝 2)引用数据类型,传递的是传递的引用地址的拷贝,而不是该对象本身
但是要注意一下String类 ,有点特别,上面代码可以看出不像引用传递,而是值传递特征,其实不然,str = "world" 相当于 str = new String("world");