java: pass

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?


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 is pass by value - always.

Here's a reference that quotes James Gosling, who should be authoritative enough for anyone:

From the authors of Java: "There is exactly one parameter passing mode in Java - pass by value - and that helps keep things simple." The Java Programming Language, 2nd ed. by Ken Arnold and James Gosling, section 2.6.1, page 40, 3rd paragraph.

链接地址: http://www.djcxy.com/p/20652.html

上一篇: C ++

下一篇: java:pass