java:按值传递或按引用传递
我有两个代码片段:
First
class PassByTest{
public static void main(String... args){
PassByTest pbt=new PassByTest();
int x=10;
System.out.println("x= "+x);
pbt.incr(x);//x is passed for increment
System.out.println("x= "+x);//x is unaffected
}
public void incr(int x){
x+=1;
}
}
在此代码中,x
的值不受影响。
第二
import java.io.*;
class PassByteTest{
public static void main(String...args) throws IOException{
FileInputStream fis=new FileInputStream(args[0]);
byte[] b=new byte[fis.available()];
fis.read(b);//how all the content is available in this byte[]?
for(int i=0;i<b.length;i++){
System.out.print((char)b[i]+"");
if(b[i]==32)
System.out.println();
}
}
}
在此,文件的所有内容都在byte[] b
中可用。
如何以及为何?
I'd two code snippets:
First
class PassByTest{
public static void main(String... args){
PassByTest pbt=new PassByTest();
int x=10;
System.out.println("x= "+x);
pbt.incr(x);//x is passed for increment
System.out.println("x= "+x);//x is unaffected
}
public void incr(int x){
x+=1;
}
}
In this code the value of x
is unaffected.
Second
import java.io.*;
class PassByteTest{
public static void main(String...args) throws IOException{
FileInputStream fis=new FileInputStream(args[0]);
byte[] b=new byte[fis.available()];
fis.read(b);//how all the content is available in this byte[]?
for(int i=0;i<b.length;i++){
System.out.print((char)b[i]+"");
if(b[i]==32)
System.out.println();
}
}
}
In this all the content of file is available in the byte[] b
.
How and Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java 始终是按值传递的。
但是,在第二种情况下,您将按值传递引用(数组是一个对象,Java 对象总是通过引用来访问)。因为该方法现在拥有对数组的引用,所以可以随意修改它。
Java is always pass-by-value.
In the second case, though, you are passing a reference by-value (an array is an object, and Java objects are always accessed via references). Because the method now has a reference to the array, it is free to modify it.
Java 是按值传递的——总是。
这里有一个参考引用了 James Gosling,他应该是对任何人来说都足够权威:
Java is pass by value - always.
Here's a reference that quotes James Gosling, who should be authoritative enough for anyone: