aspose file tools*
The moose likes Beginning Java and the fly likes passing  array  as parameter Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "passing  array  as parameter" Watch "passing  array  as parameter" New topic
Author

passing array as parameter

Rajesh Chandra
Ranch Hand

Joined: Jun 13, 2005
Posts: 55
please refer to the code below


public class MyClass{

public static void main(String[] args) {
int a = 0;
final int b = 1;
int[] c = { 2 };
final int[] d = { 3 };
useArgs(a, b, c, d);

System.out.println("INSIDE Main "+d[0]);
}

static void useArgs( final int a, int b, final int[] c, int[] d) {

d=c;

System.out.println("INSIDE METHOD "+d[0]);
}

}

The final int array d is passed as argument to the method useArgs().The final keyword is supposed to not let the reference point to any other object other than the array with element 3
but here inside the method d refers to another array c and compiler doesnt complain .why?
is it because the formal parameter is not final? However in the main method it still points to the original array.So does it infer arrays pass by value however I know it should pass by reference??

regs Rajesh
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Everything in Java is passed by value -- but variables of object type (including arrays) are references to objects, so what gets passed is the value (i.e., a copy) of that reference.

"final" affects a single variable only; you can make a copy of any final variable and modify that copy, which is what happens here.The parameter in the method is a copy of the argument you passed to it.

You might enjoy reading this and especially this.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: passing array as parameter