Assuming that the Given array is instantiated as follows: int[] given = {1, 2, 3, 4, 5};
These methods should change the array and show the print results.
public int[] change(int[] given) {
out.println(Arrays.toString(given)); //before-changes
whatIsGoingOn(given); //make changes
out.println(Arrays.toString(given));//after changes
return given; //return the supposedly changed array
}
//Make changes:
public void whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
}
I BELIVE THE PROBLEM to be with the void method, overriding the original values of the int[] given but the new initialization and declarations never make it out.
I Would expect the array to be:
{200, 0, 0, 0, 0};
But Java prints out:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
But in the case where I returned a newly changed array in the whatIsGoingOnMethod, I get my wanted results:
{1, 2, 3, 4, 5}
{200, 0, 0, 0, 0}
If the void method just does something and its not really being "applied" as I would like to expect. I'd appreciate an illuminating explanation for this.
This Question is ALREADY ANSWERED THANKS!!! I need to freeze it.
With
given = new int[5];
you are changing what the local variable given points to, not the object that it used to point to. The local is later out of scope. The array is never modified.Youre creating a whole new array, and assigning the variable that used to refer to the original to the new array. Youre modifying the new array, and never touching the old one.
The appropriate fix would be similar to what follows:
Obviously you should get rid of the extraneous code if you intend for this or similar methods to be used in actual classes.