首页 > 代码库 > java参数传递

java参数传递

1.代码示例

基本类型作为参数传递

public class TestPass1 {    public static void testPass(int t){        t = 2;    }    public static void main(String[] args){        int t = 9;        System.out.println("Before testPass: t = " + t);        testPass(t);        System.out.println("After testPass: t = " + t);    }}

结果:

Before testPass: t = 9

After testPass: t = 9

对象作为参数传递

public class TestPass2 {    public static void testPass(StringBuffer strBuf){        strBuf.append(" world");    }    public static void main(String[] args){        StringBuffer strBuf = new StringBuffer("hello");        System.out.println("Before testPass: strBuf " + strBuf);        testPass(strBuf);        System.out.println("After testPass: strBuf " + strBuf);    }}

结果:

Before testPass: strBuf hello
After testPass: strBuf hello world

对象作为参数传递

public class TestPass3 {    public static void testPass(StringBuffer strBuf){        strBuf = new StringBuffer(" world");    }    public static void main(String[] args){        StringBuffer strBuf = new StringBuffer("hello");        System.out.println("Before testPass: strBuf " + strBuf);        testPass(strBuf);        System.out.println("After testPass: strBuf " + strBuf);    }}

结果

Before testPass: strBuf hello
After testPass: strBuf hello

2.分析

1.基本类型在java中存放在堆栈中,直接存放的是

2.对象类型在java中存放在中,而堆中只是存放的该对象的地址,该对象的值放在内存中。

3.所以我们可以从上面例子中看到:

testPass1中传递的是值,所以不会改变

testPass2中其实是传递的该对象的地址,改地址指向该对象,所以会改变

testPass3中传递的是地址,但是该地址又重新指向新对象,所以不会改变

java参数传递