• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

passing array as parameter

 
Rajesh Chandra
Ranch Hand
Posts: 55
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic