【发布时间】:2012-03-12 09:03:39
【问题描述】:
我要两个代码 sn-ps:
第一
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 中找到。
如何以及为什么?
【问题讨论】:
-
int 是原始类型,byte[] 是引用类型?
-
@YuriyZubarev 所有类型,包括原始类型和引用类型,在 Java 中都是按值传递的
-
@YuriyZubarev:
doesn't guarantee to read the whole file. You need to loop.是什么意思?
标签: java pass-by-reference pass-by-value