当前位置: 技术问答>java相关
那位师兄解释一下,50分送上!
来源: 互联网 发布时间:2015-02-22
本文导语: 以下两个程序何输出的结果不同:请解释一下(点拨一下:)) //程序一MyFile1.java public class MyFile{ public static void main(String[] args){ int xx=1; bumper(xx); System.out.println(xx); } public static void bumper(int bumpMe){ bumpMe++; ...
以下两个程序何输出的结果不同:请解释一下(点拨一下:))
//程序一MyFile1.java
public class MyFile{
public static void main(String[] args){
int xx=1;
bumper(xx);
System.out.println(xx);
}
public static void bumper(int bumpMe){
bumpMe++;
}
}
运行结果为"1";
//程序二MyFile2.java
public class MyFile2{
public static void main(String args[]){
int[] myValue={1};
modifyIt(myValue);
System.out.println ("MyValue contains"+myValue[0]);
}
public static void modifyIt(int[] value){
value[0]++;
}
}
运行结果为 2
谢谢
//程序一MyFile1.java
public class MyFile{
public static void main(String[] args){
int xx=1;
bumper(xx);
System.out.println(xx);
}
public static void bumper(int bumpMe){
bumpMe++;
}
}
运行结果为"1";
//程序二MyFile2.java
public class MyFile2{
public static void main(String args[]){
int[] myValue={1};
modifyIt(myValue);
System.out.println ("MyValue contains"+myValue[0]);
}
public static void modifyIt(int[] value){
value[0]++;
}
}
运行结果为 2
谢谢
|
在JAVA中数组实际上是一个对象,所以传递数组时会将一个引用传递进去,对它的元素的修改会直接修改原始数据,对简单类型(int等)则按值传递,所以不会影响原始数据。
|
第一个参数是按值传递,bumpMe++;对xx没有影响
|
In java, if the primitive data type as a function parameters, it will act as the type "by value"; otherwise, if the object as a function parameters, it will act as the type "by reference".
Because the parameter "bumpMe" is a primitive data type, but not the parameter "value".
Because the parameter "bumpMe" is a primitive data type, but not the parameter "value".
|
void modifyIt(int[] value){
参数是按引用传递,会改变原始变量
参数是按引用传递,会改变原始变量
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。