0

I mean that when we return from that function, the address of the array remains the same address it was before we enterd the function. an example:

 class sdasd {
     public static void main(String[] args){
            int[] obj = new int [7];
            //obj has an address
            sdasd t = new sdasd();
            t.func(obj);
            //obj has the same address as before!!
            }
     void func(int[] obj){
        int[] otherObj = new int[13];
        obj=otherObj;``
        //we changed the address of the array 'obj'?
        }
   }

thanks for helping

Matt
  • 22,721
  • 17
  • 71
  • 112

3 Answers3

2

In the called function obj is copy of the reference to the array. So you have, just when you enter func, what can be described as

  main::obj --> int[7];
  func::obj --> int[7];

After assigning the new array, you have

  main::obj --> int[7];
  func::obj --> int[13];

Parameters are passed by value, so a copy of them is created. When it is a reference, the copy of the reference points to the original object; changes to the reference are local to that method (but changes to the object itself are shared by all the references!)

To put the last point in clear, if you had done, instead of assigning a new reference, something like

 void func(int[] obj) {
     obj[1] = 69;
 }

then the change would be visible from main::obj.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
1

That's because the reference to obj is passed by value into func. So in your method func, you've changed the local reference to a new array, but main's obj still refers to the original array. In Java, arrays are objects too, so arrays are declared as references just as normal objects are.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0
  • Thats because when you passed obj array to func() it actually created one copy of your array 'obj' and then passed it as parameter.

    So any changes to copy didn't affect your original 'obj'.

VishalDevgire
  • 4,232
  • 10
  • 33
  • 59