首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

提问:为啥在Operate这个方法中运行后,X的值改变,但Y没有

2012-12-19 
提问:为什么在Operate这个方法中运行后,X的值改变,但Y没有?代码:?package testpublic class Daniel {stat

提问:为什么在Operate这个方法中运行后,X的值改变,但Y没有?

代码:?

package test;public class Daniel {static void operate(StringBuffer x,StringBuffer y){System.out.println("x="+x);System.out.println("y="+y);x.append(y);System.out.println("x="+x);System.out.println("x.toString()="+x.toString());y=new StringBuffer(x.toString());System.out.println("y="+y);System.out.println("------------------------");}public static void main(String[] args) {StringBuffer a =new StringBuffer("X");StringBuffer b =new StringBuffer("Y");operate(a,b);System.out.println("a="+a);System.out.println("b="+b);System.out.println(a +","+b);}}

?

输出结果:

x=X
y=Y
x=XY
x.toString()=XY
y=XY
------------------------
a=XY
b=Y
XY,Y

?

分析:

在operate()方法中,已经将“x”,“y”重新赋值,“x”,“y”都等于xy,但是在运行operate()后面的程序时,“a”的值变成xy而“b”的值没有变,这是为什么了?

?

在主函数中调用类的含参方法的运行轨迹:

主函数注入(参数) ---->注入(参数),在类方法中运行(重新赋值和运算)--输入结果--->被其他的类的方法调用--->输出结果;

?

在这个过程中实际上是单个方法本身对注入的参数的值进行改变,并没有对注入的参数(对象本身)进行改变。所以在其他类方法调用该参数本身是,任然是初始值。在这里值得注意的是:应为StringBuffer()类中的append();insert();delete();reverse();replace()等方法,是可以对对象本进行修改和操作的...

?

扩展:

StringBuffer a =new StringBuffer("X");System.out.println("a的字符数是"+a.capacity());System.out.println("a的长度是"+a.length());

?输出结果:

--a的字符数是17
--a的长度是1

StringBuffer a=New StringBuffer(); 默认的是16char。

?

下面是一个与上面例子相关的题目,试试写出结果:

package test;public class App {int x=1;public static void getNew(int x,int y){y+=x;x+=y;System.out.println("getNew()中y="+y);System.out.println("getNew()中x="+x);}public static int getChange(int x,int y){y+=x;x+=y;return x;}void getChanged(int x,int y){y+=x;x+=y;this.x=x;}public static void main(String[] args) {int x=10;int y=5;getNew(x,y);System.out.println("x="+x+" and y="+y);getChange(x,y);System.out.println("getChange()中的x="+getChange(x,y));System.out.println("x="+x+" and y="+y);App t=new App();System.out.println("t.x="+t.x);t.getChanged(x, y);System.out.println("t.x="+t.x);System.out.println("x="+x+" and y="+y);}}

?

?

输出结果:

getNew()中y=15
getNew()中x=25
x=10 and y=5
getChange()中的x=25
x=10 and y=5
t.x=1
t.x=25
x=10 and y=5

?

原创请勿转载.......

热点排行