码迷,mamicode.com
首页 > 编程语言 > 详细

java参数传递

时间:2016-09-03 16:22:02      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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参数传递

标签:

原文地址:http://www.cnblogs.com/maying3010/p/5837227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!