Java基础-学习笔记(八)——函数的参数传递

1、基本数据类型的参数传递

 1 class PassValue
 2 {
 3     
 4     public static void main(String [] args)
 5     {
 6         int x=5;
 7         change(x);
 8         System.out.println("the current value is "+x);
 9     }
10     public static void change(int x)
11     {
12         x=3;
13     }
14 }
15 /*
16 F:\java_example>java PassValue
17 the current value is 5
18 */
View Code

实参x和形参x,虽然名字相同,但所占内存空间不一样,并且作用域也不同。形参x的作用域只限于change()中,它的取值变化是,首先取到main()中的5赋值给x,再通过change()将x的值由5变成3,最后调用change()结束,x的内存也被释放()。这一系列过程中,实参x,也就是main()中的x的值一直没有变化,所以最终打印出来为5

2、引用数据类型的参数传递

class PassValue
{
    int x;
    public static void main(String [] args)
    {
        PassValue obj = new PassValue();
        obj.x=5;
        change(obj);
        System.out.println("the current value is "+obj.x);
    }
    public static void change(PassValue obj)
    {
        obj.x=3;
    }
}
/*
F:\java_example>java PassValue
the current value is 3
*/
View Code

 

如图所示,形式参数obj是新增的一个引用句柄,其实它的作用域也只限于change函数中,但它在销毁之前,已经将对象中x的值更改,所以打印出来是3.

posted @ 2015-11-06 12:02  巅峰之旅  阅读(194)  评论(0编辑  收藏  举报