educative.io

A Bit More About Arrays

Hi, please…any one can explain me this text below in a simple way or simplify more what he want or intent !!

" In Java whenever primitive datatypes are passed as an argument to a method a copy of the variable is made and passed to that method which means if called method makes any changes to the passed values it is not visible to the calling method. As an array is a data structure rather than a primitive data type, it is passed by reference to a method which means that if the called method alters any value of an array this alteration will be visible to the calling method also."


Course: Learn Java from Scratch - Free Interactive Course
Lesson: A Bit More About Arrays - Learn Java from Scratch

Hi @ayman, basically, there are two forms of datatypes one is primitive, and the other one is non-primitive datatype. In JAVA, if we pass a parameter of primitive datatype to a function, at the time of call, a copy of that variable is passed to that function, not an original one is passed, so any changes made in that variable are not reflected in the original one.
Here is the code for primitive datatypes like int, double,float

class ArrayToMethod {
public static void main(String args[]) {
int x=10;
System.out.println(“The Value of X before calling the method is:”);
System.out.print(x);
System.out.println();
multiply(x); //nothing is being returned
System.out.println(“The Value of X after calling the method is:”);
System.out.print(x);
} //end of main()

static void multiply(int x) { 
    x=1; //will not change the value of original X
    //Not returning anything
}

}

On the other hand, non-primitive data types are passed by reference, so any changes made in the calling method will change the original values of non-primitive data types. As the array is a non-primitive data type so its values will be changed if there are any changes in the called method., here is the code for your understanding you can check by yourself.

class ArrayToMethod {
public static void main(String args[]) {
int[] arr = {
1,
2,
3,
4,
5
}; //initialize
System.out.println(“The Values before calling the method are:”);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " "); //printing the array before calling method

    }
    int[] returnedArr = multiply(arr, 3); //storing the returned array
    System.out.println();
    System.out.println("The Values from the returned Array are:");
    for (int i = 0; i < arr.length; i++) {
        System.out.print(returnedArr[i] + " "); //printing the returned array

    }
} //end of main()

static int[] multiply(int[] arr, int num) {
    for (int i = 0; i < arr.length; i++) {
        arr[i] = arr[i] * num;
    }
    return arr; //returning Array
}

}

it is very clear, thank you very much