java:按值传递或按引用传递

Moh*_*sal 0 java pass-by-reference pass-by-value

我有两个代码片段:

第一

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在此代码中,值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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,文件的所有内容都可以在byte[] b.
怎么样,为什么?

Oli*_*rth 9

Java始终是按值传递的.

但是,在第二种情况下,您将传递引用by-value(数组是一个对象,并且始终通过引用访问Java对象).因为该方法现在具有对数组的引用,所以可以自由地修改它.