Friday 18 May 2018

java: pass-by-value or pass-by-reference





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 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?


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...