0

I am declaring an array myArray in main method and passed the same array in doIt(myArray) method.

When I took another array variable in doIt() method and assign myArray to it. And then I printed the myArray in main method.

But I am doing same thing with integer and String, the changes made in respective method do not affect the output.

My Code is

public class ChangeIt {

    public static void main(String[] args) {
        int[] myArray = {1,2,3,4,5};

        new ChangeIt().doIt(myArray);
        for (int i = 0; i < myArray.length; i++) {
            System.out.print(myArray[i] + " ");
        }

        String str= "Gaurav";
        new ChangeIt().printString(str);
        System.out.println("\n"+ str);

        int num = 5;
        new ChangeIt().printNum(num);
        System.out.println(num);
    }

    private void doIt(int[] z) {
        int[] A = z;
        A[0] = 99;

    }
    private void printString(String s){
        String s2 = s + "Kukade";
    }

    private void printNum(int x) {
        int y = x+1;
    }

}

The output is

99 2 3 4 5
Gaurav
5

So, what is happening? Why it is printing 99 instead of 1?

Gaurav Kukade
  • 183
  • 2
  • 10
  • 2
    In the other two cases, you're creating new instance. In the `doIt()` method, you are just creating new variable, which points to the same instance of an array. Check this out: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1 – NeplatnyUdaj Apr 12 '19 at 12:57
  • There is a difference between *reasigning* new value and *modifying* existing value. If you want your wife to have blond hair you can either `wife = new Wife(HairColor.BLOND)` (divorce and remarry blonde) or `whife.hairColor(HairColor.BLOND);` (let your wife change her hair). Second approach (modification) also uses reassignment but it does it on object internal property (hair color) - which represents its state. – Pshemo Apr 12 '19 at 13:03
  • Thanks for your comment NeplatnyUdaj and Pshemo – Gaurav Kukade Apr 14 '19 at 18:17

1 Answers1

3

But I am doing same thing with integer and String, the changes made in respective method do not affect the output.

The fundamental difference is that with the int and String, you're not changing the state of the original int or String. In fact, you're not even assigning to the parameter (but if you did, it wouldn't be observable outside the function).

But with the array, you're changing the state of the array, not assigning a new array to a local.

This:

int[] A = z;

just points A at the same array z points to, it doesn't create a new array. Since they both point to the original array, assigning to one of its elements changes the state of the array.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875