Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

passing array as parameter  RSS feed

 
Rajesh Chandra
Ranch Hand
Posts: 55
  • 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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • 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.
 
You guys wanna see my fabulous new place? Or do you wanna look at this tiny ad?
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!