0
{
int[] n = new int[4];
n[0]=1;
n[1]=3;
n[2]=4;
n[3]=5;
for(int i=0; i<4; i++)
{
    System.out.print(n[i]+ " ");
}

menjava(n);
System.out.println();
for(int i =0;i<4;i++)
{
    System.out.print(n[i]+ " ");
}

}
public static void menjava(int[] a)
{
    a[0]=1*10;
    a[1]=3*10;
    a[2]=4*10;
    a[3]=5*10;
}
}        

https://i.stack.imgur.com/Y1Krw.jpg //the result in console

{   
int n = 1;
System.out.println(n);

menjava(n);

System.out.println(n);
}
public static void menjava(int st)
{
    st = 4;
}
}    

https://i.stack.imgur.com/EVSeU.jpg //the result in console

So why did the Array get returned, but the integer stayed the same (whcih in my mind should). I can't find anything on why the array get's returned in an void function.

Eric
  • 200
  • 6
Nino Klajnsek
  • 29
  • 1
  • 5
  • [This answer in particular](http://stackoverflow.com/a/12429953/1361506) has an in-depth and well-diagrammed explanation of what happens when you modify objects that are passed as a parameter to a method (keep in mind that in Java, all arrays are objects, even if they are arrays of a primitive type). – azurefrog Dec 10 '15 at 22:28
  • In short: Java passes references by value. You can change _properties of objects_ in a method and those changes will be reflected in the caller, including array elements, but you cannot change references themselves or primitives in methods and have the changes reflected in the caller. – Louis Wasserman Dec 10 '15 at 22:56

2 Answers2

0

The reference to the array is not returned nor changed.

The array referenced has been changed.

int[] n = new int[4];

In this code n is a reference to an array and this reference is copied when you pass it to a method. This reference is not changed.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Your issue here is that Java is a pass by value language. This means in your situation you are providing your method menjava with what might as well be a temporary array that contains the same values as your original array n. So when this array is passed to menjava it does the calculations, but to this temporary array that your main method doesn't know about.

The easiest fix here is to have your menjava method return the array it worked on and set your array to that value in the calling function something like this:

public static int[] menjava(int[] a){

    //changes to array a

    return a;

}

and then in your calling function:

{
    //your other code
    n = menjava(n);
    //the rest of your code
}
Geoff
  • 1