• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

passing array as parameter

 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic